When unsigned/signed long int a; is possible why unsigned/signed long float/double a; is not possible ?
Why do I get too many types in declaration error for the latter and not for the former ?
When unsigned/signed long int a; is possible why unsigned/signed long float/double a; is not possible ?
Why do I get too many types in declaration error for the latter and not for the former ?
I have not read the C++ standard but this is how I feel like unordered_map in c++ suppose to work.
I am quite surprised that I could not find much about how the memory is handled by unordered_map. Is there a specific initial size of memory which unordered_map allocates. What happens if lets say we allocated 50 int memory and we ended up inserting 5000 integer?
This will be lot of collisions so I believe there should be kind of like a rehashing and re-sizing mechanism to decrease the number of collisions after a certain level of collision threshold is reached. Since they are explicitly provided as member functions to the class, I assume they are used internally as well. Is there a such mechanism?
Below is my implementation to keep track of the size of each tree in the disjoint set forest.
Can you please tell me what is wrong with it ? I am trying to solve UVa problem https://goo.gl/ZiQCyH
#include <iostream>
#include <cstdio>
#include <unordered_map>
using namespace std;
class Node {
public :
int id;
Node *parent;
unsigned long long rank;
Node(int id) {
this->id = id;
// this->data = data;
this->rank =1; //size here
this->parent = this;
}
friend class DisjointSet;
};
class DisjointSet {
unordered_map<int,Node*> nodesMap;
Node *find_set_helper(Node *aNode) {
if (aNode == aNode->parent) {
return aNode->parent;
}
return find_set_helper(aNode->parent);
}
void link(Node *xNode,Node *yNode) {
if( xNode->rank > yNode->rank) {
yNode->parent = xNode;
xNode->rank += yNode->rank;
}
// else if(xNode-> rank < yNode->rank){
// xNode->parent = yNode;
// yNode->rank += xNode->rank;
// }
else {
xNode->parent = yNode;
yNode->rank += xNode->rank;
}
}
public:
DisjointSet() {
}
void AddElements(int sz) {
for(int i=0;i<sz;i++)
this->make_set(i);
}
void make_set(int id) {
Node *aNode = new Node(id);
this->nodesMap.insert(make_pair(id,aNode));
}
void Union(int xId, int yId) {
Node *xNode = find_set(xId);
Node *yNode = find_set(yId);
if(xNode && yNode)
link(xNode,yNode);
}
Node* find_set(int id) {
unordered_map<int,Node*> :: iterator itr = this->nodesMap.find(id);
if(itr == this->nodesMap.end())
return NULL;
return this->find_set_helper(itr->second);
}
~DisjointSet(){
unordered_map<int,Node*>::iterator itr;
for(itr = nodesMap.begin(); itr != nodesMap.end(); itr++) {
delete (itr->second);
}
}
};
int main() {
int n,m,k,first,cur;
//freopen("in.in","r",stdin);
scanf("%d %d",&n,&m);
while(n != 0 || m != 0) {
DisjointSet *ds = new DisjointSet();
ds->AddElements(n); // 0 to n-1
//printf("\n n = %d m = %d",n,m);
for(int i=1;i<=m;i++) {
scanf("%d",&k);
//printf("\nk=%d",k);
if ( k > 0 ) {
scanf("%d",&first);
for(int j=2;j<=k;j++) {
scanf("%d",&cur);
ds->Union(first,cur);
}
}
}
Node *zeroSet = ds->find_set(0);
// unsigned long long count = ds->getCount(zeroSet->id);
printf("%llu\n",zeroSet->rank);
delete ds;
scanf("%d %d",&n,&m);
}
return 0;
}
The link function in the above code does the job of updating the tree size.
The solution to the problem is to find the set which elements 0 belongs to and get the size of the representative element of the set. But I am getting wrong answer with this code.
Can you please help me
I tried building the sample code on QT Creator that DJI released to test out on their drones, however, whenever I try building the sample code, it always gives me a bunch of errors and I'm not sure why. I've just begun using it so I don't know much about a lot of stuff and I just followed the directions on the manual that came with all the files so it'll be great if someone knew how to fix this problem
I am a beginner in C++ and I have attempted to follow the instructions here to the letter for setting up SFML in code::blocks:
After following all the instructions I still get the following error message:
I have no idea what this means. Could someone please explain in very basic terms what I need to do from here?
I am trying to run my first SFML application. I can run it via Code Blocks environment, but I can't run it through the Explorer - an error appears that says: "libgcc_s_sjlj-1.dll is missing". I added these lines to my linker options:
-static
-static-libgcc
-static-libstdc++
However, after trying to compile it, I see an error in the build log:
mingw32-g++.exe: error: unrecognized command line option '-static-libstdc++'
How can I fix it? My GCC version is 4.7.1 TDM-1
Can anyone provide me C/C++ code for following command???
$ gst-launch-1.0 filesrc location=~/Desktop/test.mp4 ! decodebin name=dec
! videoconvert ! autovideosink dec. ! audioconvert ! audioresample ! alsasink
I am studying a parameterized system of stiff ODEs and need to solve it for many values of its parameters. I am working in C/C++/CUDA and I want to solve these systems in parallel.
I was wondering if I could use odeint for this. I found this example, but according to this page of the documentation, stiff solvers require ublas types.
Does it mean that their stiff solvers are incompatible with Thrust?
I am making a Pentago game for someone, and I wanted to write a good code, so I decided to use operator overloading.
We have 2 classes; first one is Block class (which represents every single block of the board) and the second one is Set class (which represents a 3*3 table of blocks). Now I want to use Set as a 2d array so I can use set[foo][foo]. Can you help me to make an operator like this?
I have created a Win32 Console Application project in Visual Studio 2012 C++, and now I would like to substitute the Console window by a more appealing GUI. I'm thinking of using Windows Forms, it's possible to do this? And if so, can someone give me a brief explanation of how to do it?
Here I copy a piece of the Console Application code that I would like to run through a Windows Form:
int32_t main(int32_t argc, char* argv[])
{
const char *date = "20150428_1\\";
int mode=0;
_CallServerPtr pCallServer;
uint32_t start_address_comp=0;
uint32_t start_address_module=0;
const char* xmlFile_tx_dbb="tx_dbb.xml";;
char str[100] = "\0";
char localeStr[64];
memset(localeStr, 0, sizeof localeStr);
const char *l_path = "..\\XERCES\\Configs\\";
std::string buf = "";
double Fsym_Hz=(1/1.15)*1e9;
int selection=0;
int user_selection=0;
try
{
if (strlen(localeStr))
{
XMLPlatformUtils::Initialize(localeStr);
}
else
{
XMLPlatformUtils::Initialize();
}
}
catch (const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"
<< StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
}
static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
DOMLSParser *parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
DOMConfiguration *config = parser->getDomConfig();
DOMLSSerializer *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
DOMLSOutput *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();
config->setParameter(XMLUni::fgDOMDatatypeNormalization, true);
DOMCountErrorHandler errorHandler;
config->setParameter(XMLUni::fgDOMErrorHandler, &errorHandler);
XERCES_STD_QUALIFIER ifstream fin;
//reset error count first
errorHandler.resetErrors();*/
// reset document pool
parser->resetDocumentPool();
char* pszHostname = NULL;
pSaIn = 0;
pSaOut = 0;
// Initialize the COM Library
CoInitialize(NULL);
if (!pszHostname)
{
// Create the CallServer server object on the local computer
pCallServer.CreateInstance(CLSID_CallServer);
}
if (pCallServer == NULL)
throw "Failed to create the CallableVEE CallServer object";
// Load the VEE User Function library
char strpath[256];
strcpy (strpath,reposity_path);
strcat (strpath,l_path_vee);
_bstr_t bstrLibPath(strpath);
LibraryPtr pLib = pCallServer->GetLibraries()->Load(bstrLibPath);
// Print out the names of the UserFunctions in this library.
UserFunctionsPtr pUserFuncColl = pLib->GetUserFunctions();
VARIANT_BOOL bDebug = VARIANT_FALSE;
pCallServer->PutDebug(bDebug);
// Variables added by ivi
float *freq =(float *)_aligned_malloc(6,16); // Read frequency vector
// Previous variables
int32_t devIdx;
int32_t modeClock;
int32_t ifType;
const char *devType;
char fpga_device_type[32];
int32_t rc;
int32_t ref_clk=0;
uint32_t carrier=0;
uint32_t odelay_dac0 = 0;
uint32_t odelay_dac1 = 0;
// Parse the application arguments
if(argc!=5) {
printf("Usage: FMCxxxApp.exe {interface type} {device type} {device index} {clock mode} \n\n");
printf(" {interface type} can be either 0 (PCI) or 1 (Ethernet). At CEIT, we use 1 (Ethernet).\n");
printf(" {device type} is a string defining the target hardware (VP680, ML605, ...). At CEIT, we use VC707.\n");
printf(" {device index} is a PCI index or an Ethernet interface index. This value depends on the PC.\n");
printf(" {clock mode} can be either 0 (Int. Clock) or 1 (Ext. Clock)\n");
printf("\n");
printf("\n");
printf("Example: Fmc230APP.exe 1 VC707 0 0\n");
printf("\n");
printf("\n");
printf(" List of NDIS interfaces found in the system {device index}:\n");
printf(" -----------------------------------------------------------\n");
if(sipif_getdeviceenumeration(API_ENUM_DISPLAY)!=SIPIF_ERR_OK) {
printf("Could not obtain NDIS(Ethernet) device enumeration...\n Check if the 4dspnet driver installed or if the service started?\n");
printf("You can discard this error if you do not have any Ethernet based product in use.");
}
if( EXIT_IF_ERRORS)
{
sipif_free();
system("pause");
return -1;
}
...
}
Thank you very much in advance.
I'm a C++ programmer, who's still in the nest, and not yet found my wings. I was writing a Calendar program, and I discovered, that C++ does not support a string type. How do I make an Array, that will be able to store strings of characters?
I've thought of creating an enumerated data type, as the array type. While, it will work, for my Calendar, it won't work if say I was creating a database of the names of students in my class.
http://ift.tt/1NnnPZv I got; "error, 'string' does not name a type."
I am trying to forcefully release a named Mutex that another process owns in my process. However, when I try to straight up release the mutex like so, I get the error 288 (ERROR_NOT_OWNER). Clearly, I need to take ownership of the Mutex.
I've tried using GetSecurityInfo and SetSecurityInfo but they seem to be not working.
HANDLE hMyToken;
OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hMyToken);
PTOKEN_OWNER pMe = NULL;
DWORD dwLength = 0;
GetTokenInformation(hMyToken, TokenOwner, pMe, NULL, &dwLength);
pMe = (PTOKEN_OWNER)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
GetTokenInformation(hMyToken, TokenOwner, pMe, dwLength, &dwLength);
I use the code above to get the current PSID for the owner for later.
HANDLE hMutex = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, "mutexnamehere");
PSID psidOwner = NULL;
PSECURITY_DESCRIPTOR psd;
GetSecurityInfo(hMutex, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, &psidOwner, NULL, NULL, NULL, &psd);
PSECURITY_DESCRIPTOR psda = NULL;
DWORD dwLength = 0, dwLength2 = sizeof(psidOwner), dwGarbage;
MakeAbsoluteSD(psd, psda, &dwLength, NULL, &dwGarbage, NULL, &dwGarbage, psidOwner, &dwLength2, NULL, &dwGarbage);
psda = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
psidOwner = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength2);
MakeAbsoluteSD(psd, psda, &dwLength, NULL, &dwGarbage, NULL, &dwGarbage, psidOwner, &dwLength2, NULL, &dwGarbage);
etSecurityInfo(hMutex, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, pMe->Owner, NULL, NULL, NULL);
I've been stuck on this for hours. Can anyone give me an idea on what to do? I've tried:
I cannot open the process that owns the Mutex nor can I inject code into that process or enumerate its handles and forcefully close it.
I'm willing to map the Mutex to memory and work with it there.
I am using OpenCL for stereo image processing and after I ported a C++ implementation to OpenCL i was playing around with optimizations. A very simple experiment was to swap around the dimensions.
Consider a simple kernel, which is executed for every pixel along the two dimensional work space (f.e. 640x480). In my case it was a Census transform.
Swapping from:
int globalU = get_global_id(0);
int globalV = get_global_id(1);
too
int globalU = get_global_id(1);
int globalV = get_global_id(0);
while adjusting the NDRange in the same way, gave a performance boost about 500%. Other experiments in 3d Space achieved a execution time from 72ms to 2ms, only with reordering of the dimensions.
Can anybody explain my, how this happens? Is it just an effect of memory pipelines and cache usage?
EDIT: The image has a standart mamory layout. Thats why i wondered about the effects. I expected the best speed, when the iteration goes like the image is stored in the memory, which is not the case.
After some reading of the AMD APP SDK documantation, i foudn some interesting details about the memory channels. That could be a reason.
This question already has an answer here:
C++ allows template arguments that refer to template classes, not instances of it. For example the function fun below.
At the same time there is a feature by which template arguments can be omitted inside a class definition. For example in the definition of template<class T> class A, we can say A to imply A<T>.
I found a case where both rules potentially can produce an ambiguity. Moreover I cannot solve the ambiguity. Here it is a MWE, in which in the definition of template<class T> class B I need to refer to B as a template class and not as B<T>.
template <template<class> class Y, class T>
auto fun(){return Y<T>{};} // fun can be used with a *template* class
template<class T>
struct A{
friend void f(A a){} //A here is implicitly A<T>, ok
};
template<class T>
struct B{
friend void g(B b){
fun<A, void>(); // here A is a template class, ok
fun<B, void>(); // error: no matching function for call to 'fun' because the compiler sees B<T>, not B
} //A here is implicitly A<T>,
};
int main(){
A<void> a{};
B<void> b{};
g(b);
}
(I need to do this because the function g is a friend function that I want to define inside the class.)
Clang 3.5 gives the error described above, and GCC 4.9.2 is ok with it. The worst part is that I cannot make additional specifications and resolve the ambiguity.
For example I tried:
fun<struct B, void>();
fun<template<class> struct B, void>();
but still get the same error.
Is there a way to tell clang (or a problematic compiler) that B is not B<T> but the template class B?
(I used some C++11 syntax to simplify the example, but the problem iapplies to C++98 as well. Please correct or let me know if I am not using the right naming conventions.)
Thanks to @dyp and @T.C. I could write two three solutions:
0) cast the magic spell B::template B
template<class T>
struct B{
friend void g(B b){
fun<A, void>(); // here A is a template class, ok
fun<B::template B, void>(); // no error now
} //A here is implicitly A<T>,
};
1) specify namespace somehow (needs to know the enclosing namespace)
template<class T>
struct B{
friend void g(B b){
fun<A, void>(); // here A is a template class, ok
fun<::B, void>(); // no error now
} //A here is implicitly A<T>,
};
2) Define alias template
template<class T>
struct B{
template<class TT> using BB = B<TT>; // couldn't put inside the g function
friend void g(B b){
fun<A, void>(); // here A is a template class, ok
fun<BB, void>(); // no error
} //A here is implicitly A<T>,
};
(none of the two is ideal, but it is a good workaround) The first is an ideal workaround.
I am reading an uint16 from a sensor connected to an raspberry (arm). I convert the data from little endian to big endian via:
// result = 0A0B0C0D 0E0F0A0B
// 0E0F0A0B 00000000 | 00000000 0A0B0C0D
((result << 8) & 0xFF00) | (result >> 8);
So 0A0B0C0D 0E0F0A0B is 0E0F0A0B 0A0B0C0D afterwards.
But I also saw people using this:
((result << 8) & 0xFF00) + (result >> 8);
Is there any advantage of using the addition? My guess is, there is no really advantage, it is just a bit slower.
There is a big difference when it comes to sum two numbers for example:
EF10 = 0FF0 + 00FF != 0FF0 | 00FF = 0FFF
Maybe I answered my own question already but it would be nice, if someone could evaluate. Would not be the first time I am tricking myself.
I have the following three files, of which I cannot find the source of an error that it is producing:
Main.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include "ResourceHolder.h"
namespace Textures
{
enum ID { Landscape, Airplane, Missile };
}
int main()
{
//...
try
{
ResourceHolder<sf::Texture, Textures::ID> textures;
textures.load(Textures::Airplane, "Airplane.png");
}
catch (std::runtime_error& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
//...
}
ResourceHolder.h
#pragma once
#include <map>
#include <string>
#include <memory>
#include <stdexcept>
#include <cassert>
template <typename Resource, typename Identifier>
class ResourceHolder
{
public:
void load(Identifier id, const std::string& fileName);
Resource& get(Identifier id);
const Resource& get(Identifier id) const;
private:
void insertResource(Identifier id, std::unique_ptr<Resource> resource);
std::map<Identifier, std::unique_ptr<Resource>> mResourceMap;
};
ResourceHolder.cpp
#include "ResourceHolder.h"
template <typename Resource, typename Identifier>
void ResourceHolder<Resource, Identifier>::load(Identifier id, const std::string& fileName)
{
//Create and load resource
std::unique_ptr<Resource> resource(new Resource());
if (!resource->loadFromFile(fileName)) {
throw std::runtime_error("ResourceHolder::load - Failed to load " + fileName);
}
//If loading was successful, insert resource to map
insertResource(id, std::move(resource));
}
template <typename Resource, typename Identifier>
Resource& ResourceHolder<Resource, Identifier>::get(Identifier id)
{
auto found = mResourcemap.find(id);
assert(found != mResourceMap.end());
return *found->second();
}
template <typename Resource, typename Identifier>
void ResourceHolder<Resource, Identifier>::insertResource(Identifier id, std::unique_ptr<Resource> resource)
{
//Insert and check success
auto inserted = mResourceMap.insert(std::make_pair(id, std::move(resource)));
assert(inserted.second);
}
If I were to remove the try-catch combination in main.cpp, the code compiles fine; However, if I leave it there it gives me an LNK2019 (Unresolved external symbol) Error.
What is the source of this error, and how would I fix it?
I'm trying to do FFT on a 2D matrix of complex numbers, where the real and the imaginary parts are held in different locations (not interleaved). The data is organized in row-major.
The program crashes (segfault) on fftw_execute_split_dft.
This is the code I use, based on (PDF): http://ift.tt/1GERuIH
bool FFTNDSplit(int NumDims, const int N[], double *XReal, double *XImag, double *YReal, double *YImag, int Sign)
{
fftw_plan Plan;
fftw_iodim Dim[NumDims];
int k, NumEl;
for(k = 0, NumEl = 1; k < NumDims; k++)
{
Dim[k].n = N[k];
Dim[k].is = Dim[k].os = 1;
NumEl *= N[k];
}
if(!(Plan = fftw_plan_guru_split_dft(NumDims, Dim, 0, NULL, XReal, XImag, YReal, YImag, FFTW_ESTIMATE)))
return false;
if (Sign == -1) { // FFT
fftw_execute_split_dft(Plan, XReal, XImag, YReal, YImag);
} else { // IFFT
fftw_execute_split_dft(Plan, XImag, XReal, YImag, YReal);
DivideArray(YReal, NumEl, static_cast<double>(NumEl));
DivideArray(YImag, NumEl, static_cast<double>(NumEl));
}
fftw_destroy_plan(Plan);
return true;
}
I suspect it has something to do with Dim configuration of strides, that's the part of the code I changed from the example, since row-major data is used rather than col-major.
How should a 2D matrix row-major should be configured to use the guru interface?
I like to extract a foreground image with one of the OpenCV background subtraction methods (BackgroundSubtractorKNN,BackgroundSubtractorMOG2 or BackgroundSubtractorGMG) with sometimes complicated conditions.
However, I have a priori data for a part of the image, describing the propability of each pixel to classify as foregorund or background.
Is it possible with any of this algorithms above to feed my prior data for increased quality? Or maybe any pre / post operation that would make use of it and also affect the background training?
I want to render an image on the sphere with any type(e.g jpg tif bmp). so I try the opencv and opengl to do this work. but Iam new for opengl.
below is the code i used.
void createTex(Mat &img)
{
glGenTextures(2, m_texnames);
glBindTexture(GL_TEXTURE_2D, m_texnames[0]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPLACE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPLACE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, img.cols, img.rows, GL_BGR_EXT, GL_UNSIGNED_BYTE, img.data);
}
void sphere()
{
glEnable(GL_TEXTURE_2D);
createTex(src);
glBindTexture(GL_TEXTURE_2D, m_texnames[0]);
glPushMatrix();
gluQuadricTexture(g_text, GLU_TRUE);
gluQuadricDrawStyle(g_text, GLU_FILL);
gluSphere(g_text, 1.0, 64, 64); /*draw sun */
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
virtual void onDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
validateCameraPosition();
validateModelPosition();
sphere();
glFlush();
glutSwapBuffers();
}
I cant post a picture for now ; eee.........eee the picture is very normal (a earth map from wiki), as below.
but ,there is a fault on the sphere when I change the view postion. is there a mistake in my code? and some one can tell why it occurs?
//update:2015.06.28
finally, i found the mistake. the function gluPerspective() cant take 0.0f that specifies the distance from the viewer to the near clipping plane; i think the 0.0f may disturb the project matix; so the value must be bigger than zero; below is the code dismistaked;
virtual void onResize(int w, int h)
{
printf("resize window: %d, %d\n", w, h);
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//gluPerspective(100.0,(GLfloat)w / (GLfloat)h, 0.0/*wrong*/, 20.0);
gluPerspective(100.0, (GLfloat)w / (GLfloat)h, 0.1, 20.0);
//glOrtho(-1, 1, -1, 1,0,20);
}
I am trying to use Noxim for NOC. The SystemC library is working properly but Noxim gives error
std::size_t
The file which is giving error is NoximMain.cpp
/*
* Noxim - the NoC Simulator
*
* (C) 2005-2010 by the University of Catania
* For the complete list of authors refer to file ../doc/AUTHORS.txt
* For the license applied to these sources refer to file ../doc/LICENSE.txt
*
* This file contains the implementation of the top-level of Noxim
*/
#include "NoximMain.h"
#include "NoximNoC.h"
#include "NoximGlobalStats.h"
#include "NoximCmdLineParser.h"
#include "NoximLog.h"
#include <sys/stat.h>
using namespace std;
// need to be globally visible to allow "-volume" simulation stop
unsigned int drained_volume;
// Log file stream
ofstream results_log_pwr; //Initial in NoximLog, record in thermal_IF.cpp
ofstream transient_log_throughput; //Initial in NoximLog, record in NoximNoC.cpp
ofstream transient_topology;
// Initialize global configuration parameters (can be overridden with command-line arguments)
int NoximGlobalParams::verbose_mode = DEFAULT_VERBOSE_MODE;
int NoximGlobalParams::trace_mode = DEFAULT_TRACE_MODE;
char NoximGlobalParams::trace_filename[128] = DEFAULT_TRACE_FILENAME;
int NoximGlobalParams::mesh_dim_x = DEFAULT_MESH_DIM_X;
int NoximGlobalParams::mesh_dim_y = DEFAULT_MESH_DIM_Y;
int NoximGlobalParams::mesh_dim_z = DEFAULT_MESH_DIM_Z;
int NoximGlobalParams::buffer_depth = DEFAULT_BUFFER_DEPTH;
int NoximGlobalParams::min_packet_size = DEFAULT_MIN_PACKET_SIZE;
int NoximGlobalParams::max_packet_size = DEFAULT_MAX_PACKET_SIZE;
int NoximGlobalParams::routing_algorithm = DEFAULT_ROUTING_ALGORITHM;
char NoximGlobalParams::routing_table_filename[128] = DEFAULT_ROUTING_TABLE_FILENAME;
int NoximGlobalParams::selection_strategy = DEFAULT_SELECTION_STRATEGY;
float NoximGlobalParams::packet_injection_rate = DEFAULT_PACKET_INJECTION_RATE;
float NoximGlobalParams::probability_of_retransmission = DEFAULT_PROBABILITY_OF_RETRANSMISSION;
int NoximGlobalParams::traffic_distribution = DEFAULT_TRAFFIC_DISTRIBUTION;
char NoximGlobalParams::traffic_table_filename[128] = DEFAULT_TRAFFIC_TABLE_FILENAME;
int NoximGlobalParams::simulation_time = DEFAULT_SIMULATION_TIME;
int NoximGlobalParams::stats_warm_up_time = DEFAULT_STATS_WARM_UP_TIME;
int NoximGlobalParams::rnd_generator_seed = time(NULL);
bool NoximGlobalParams::detailed = DEFAULT_DETAILED;
float NoximGlobalParams::dyad_threshold = DEFAULT_DYAD_THRESHOLD;
unsigned int NoximGlobalParams::max_volume_to_be_drained = DEFAULT_MAX_VOLUME_TO_BE_DRAINED;
vector <pair <int, double> > NoximGlobalParams::hotspots;
int NoximGlobalParams::dw_layer_sel = DEFAULT_DW_LAYER_SEL;
int NoximGlobalParams::throt_type = DEFAULT_THROTTLING_TYPE;
int NoximGlobalParams::down_level = DEFAULT_DOWN_LEVEL;
float NoximGlobalParams::throt_ratio = DEFAULT_THROTTLING_RATIO;
bool NoximGlobalParams::buffer_alloc = DEFAULT_BUFFER_ALLOC;
int NoximGlobalParams::vertical_link = DEFAULT_VERTICAL_LINK;
bool NoximGlobalParams::cascade_node = DEFAULT_CASCADE_NODE;
bool NoximGlobalParams::Mcascade = DEFAULT_MCASCADE;
int NoximGlobalParams::Mcascade_step = 0;
bool NoximGlobalParams::beltway = DEFAULT_BELTWAY;
float NoximGlobalParams::beltway_trigger = TEMP_THRESHOLD;
bool NoximGlobalParams::Mbeltway = DEFAULT_MBELTWAY;
bool NoximGlobalParams::Sbeltway = DEFAULT_SBELTWAY;
int NoximGlobalParams::Sbeltway_ring = 0;
int NoximGlobalParams::ROC_UP = 4;
int NoximGlobalParams::ROC_DOWN = 3;
float NoximGlobalParams::beltway_ratio = 0.25;
bool NoximGlobalParams::Log_all_Temp = false;
int NoximGlobalParams::clean_stage_time = 3000;
bool NoximGlobalParams::cal_temp = DEFAULT_CAL_TEMP;
int NoximGlobalParams::br_sel = INVALID_SELECTION;
bool NoximGlobalParams::message_level = DEFAULT_MESSAGE_LEVEL;
int NoximGlobalParams::dynamic_throt_case = -1;
//---------------------------------------------------------------------------
int sc_main(int arg_num, char *arg_vet[])
{
// TEMP
drained_volume = 0;
// Handle command-line arguments
cout << endl << "\t\tNoxim - the NoC Simulator" << endl;
cout << "\t\t(C) University of Catania" << endl << endl;
parseCmdLine(arg_num, arg_vet);
// Signals
sc_clock clock("clock", 1, SC_NS);
sc_signal <bool> reset;
// NoC instance
NoximNoC *n = new NoximNoC("NoC");
n->clock(clock);
n->reset(reset);
//Log files
NoximLog log;
if(!mkdir("results",0777)) cout<<"Making new directory results"<<endl;
if (NoximGlobalParams::trace_mode)log.TraceSignal(n);
log.PowerLog();//Transient power tracefile
log.Throughput();
// Reset the chip and run the simulation
reset.write(1);
cout << "Reset...";
srand(NoximGlobalParams::rnd_generator_seed); // time(NULL));
//DEFAULT_RESET_TIME = # of simulation cycle
sc_start(DEFAULT_RESET_TIME * CYCLE_PERIOD + 1, SC_NS);
reset.write(0);
cout << " done! Now running for " << NoximGlobalParams::
simulation_time << " cycles..." << endl;
// sc_start( TEMP_REPORT_PERIOD - DEFAULT_RESET_TIME * CYCLE_PERIOD , SC_NS);
// int i;
// for ( i = TEMP_REPORT_PERIOD ; i < NoximGlobalParams::simulation_time ; i += TEMP_REPORT_PERIOD ){
// reset.write(1);
// sc_start( DEFAULT_RESET_TIME * CYCLE_PERIOD , SC_NS);
// reset.write(0);
// cout<<getCurrentCycleNum()<<": Reset done."<<endl;
// sc_start( TEMP_REPORT_PERIOD - DEFAULT_RESET_TIME * CYCLE_PERIOD , SC_NS);
// cout<<getCurrentCycleNum()<<" cycles run"<<endl;
// }
// sc_start(NoximGlobalParams::simulation_time * CYCLE_PERIOD - getCurrentCycleNum() , SC_NS);
sc_start(NoximGlobalParams::simulation_time * CYCLE_PERIOD , SC_NS);
// Close the simulation
cout << "Noxim simulation completed." << endl;
cout << " ( " << getCurrentCycleNum() << " cycles executed)" << endl;
if (NoximGlobalParams::trace_mode)log.TraceEnd();
log.BufferLog(n);
log.TrafficLog(n);
log.PowerLogEnd();
log.ThroughputEnd();
// Show statistics
NoximGlobalStats gs(n);
gs.showStats(std::cout, NoximGlobalParams::detailed);
if ((NoximGlobalParams::max_volume_to_be_drained > 0) && getCurrentCycleNum() >= NoximGlobalParams::simulation_time ) {
cout << "\nWARNING! the number of flits specified with -volume option" << endl;
cout << "has not been reached." << endl;
cout << "You might want to try an higher value of simulation cycles" << endl;
cout << "using -sim option." << endl;
cout << "\n Effective drained volume: " << drained_volume << endl;
}
return 0;
}
The log or errors on my terminal are as follow.
C(sc_core::sc_module_name)]+0x420): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x42c): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x54f): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x56f): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x583): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x58a): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x59b): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5c6): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5ce): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5da): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x6fd): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x71d): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x731): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x738): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x749): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x774): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x77c): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x788): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x8ab): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x8cb): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x8df): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x8e6): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x8f7): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x922): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x92a): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x936): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xa5a): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xa7a): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xa8e): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xa95): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xaa6): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:((.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5784): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x578b): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x579c): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x57c7): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x57cf): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x57db): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x58fe): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x591e): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5932): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5939): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x594a): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5975): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x597d): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x5989): undefined reference to `vtable for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x9253): undefined reference to `sc_core::sc_process_b::m_delete_next_p'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x9265): undefined reference to `sc_core::sc_process_b::m_delete_next_p'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x9272): undefined reference to `sc_core::sc_process_b::m_delete_next_p'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x92da): undefined reference to `sc_core::sc_process_b::m_delete_next_p'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x92ec): undefined reference to `sc_core::sc_process_b::m_delete_next_p'
./NoximMain.o:NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0x92f9): more undefined references to `sc_core::sc_process_b::m_delete_next_p' follow
./NoximMain.o: In function `NoximNoC::NoximNoC(sc_core::sc_module_name)':
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xca9a): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xcaaa): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xcac1): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xcad8): undefined reference to `VTT for sc_core::sc_signal<bool>'
NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xcadf): undefined reference to `VTT for sc_core::sc_signal<bool>'
./NoximMain.o:NoximMain.cpp:(.text._ZN8NoximNoCC1EN7sc_core14sc_module_nameE[NoximNoC::NoximNoC(sc_core::sc_module_name)]+0xcbbd): more undefined references to `VTT for sc_core::sc_signal<bool>' follow
./thermal_IF.o: In function `__static_initialization_and_destruction_0(int, int)':
thermal_IF.cpp:(.text+0x3d): undefined reference to `sc_core::sc_api_version_2_2_0::sc_api_version_2_2_0()'
./NoximVLink.o: In function `__static_initialization_and_destruction_0(int, int)':
NoximVLink.cpp:(.text+0xbd): undefined reference to `sc_core::sc_api_version_2_2_0::sc_api_version_2_2_0()'
./NoximLog.o: In function `__static_initialization_and_destruction_0(int, int)':
NoximLog.cpp:(.text+0x3d): undefined reference to `sc_core::sc_api_version_2_2_0::sc_api_version_2_2_0()'
collect2: error: ld returned 1 exit status
Kindly help me to solve this problem. Thanks in Advance.
I have an event in one thread and need to invoke handler function in another. Usually I use function connect(), but in case of two threads I had an error:
QObject::connect: Cannot queue arguments of type 'QVector<unsigned char>'
(Make sure 'QVector<unsigned char>' is registered using qRegisterMetaType().)
I tried to use qRegisterMetaType(), but don't understood clearly how and where should I declare it. I wrote code sample, which just invoke execution in thread0 from thead1. I didn't include my attempts of using qRegisterMetaType() because they all failed =)
thread0.h:
#ifndef THREAD0_H
#define THREAD0_H
#include <QThread>
#include <QVector>
class thread0 : public QThread
{
Q_OBJECT
public:
thread0();
~thread0();
protected:
void run() Q_DECL_OVERRIDE;
public slots:
void printBuff(QVector<unsigned char> vec);
};
#endif // THREAD0_H
thread1.h:
#ifndef THREAD1_H
#define THREAD1_H
#include <QThread>
#include <QVector>
class thread1 : public QThread
{
Q_OBJECT
public:
thread1();
~thread1();
protected:
void run() Q_DECL_OVERRIDE;
signals:
void sendToPrint(QVector<unsigned char> vec);
};
#endif // THREAD1_H
main.cpp:
#include <QCoreApplication>
#include "thread0.h"
#include "thread1.h"
#include <QObject>
#include <QMetaType>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
thread0 *th0 = new thread0();
thread1 *th1 = new thread1();
QObject::connect(th1, &thread1::sendToPrint, th0, &thread0::printBuff);
th0->start();
th1->start();
return a.exec();
}
and thread1.cpp:
#include "thread1.h"
thread1::thread1()
{
}
thread1::~thread1()
{
}
void thread1::run()
{
QVector<unsigned char> vec = {0, 1, 2, 3};
emit sendToPrint(vec);
}
P.S. If I use direct connection code works.
QObject::connect(th1, &thread1::sendToPrint, th0, &thread0::printBuff, Qt::DirectConnection);
Transitioning from C++ into web development and am curious about BST and data structures in general in AngularJS.
I would like to create a BST with a breadth-first search option. In C++, I'd create a node with a left and right pointer. Then use a queue to enqueue the root node, see if matches the desired value and if it does not, push the child elements and dequeue the root.
I am not really sure where to begin with this in AngularJS, as there are no nodes and pointers. It seems the functionality for creating/manipulating your own datastructures is not as flexible. When performing an $http.get(), I would like to store the data in a BST and search for items with BFS.
Can anyone suggest a starting place? Would using pure JavaScript to create a custom data structure be preferrable?
I want to check if a character is printable, but the input comes from the user so I cannot be sure it is ASCII. I tried to use the wide functions, but it does not work.
See this little program:
#include <iostream>
#include <clocale>
#include <string>
int main() {
std::setlocale(LC_ALL, "");
std::wstring str{};
std::wcin >> str;
std::wcout << "\n";
for (auto& c : str) {
if (std::isprint(c))
std::wcout << c << " is printable\n";
else
std::wcout << c << " is NOT printable\n";
}
std::wcout "\n" << str << std::endl;
}
It compiles fine, but the result works only for the second and third character!
% ./test
かたな
か is NOT printable
た is printable
な is printable
かたな
What am I missing? Is there a way to check if a character is printable that works from standard input whatever locale is there? Or something more generic depending on the encoding?
I would like to display my x axis in the hh:mm:ss format. It basicaly works, but there is one problem. The displayed time doesnt start from 00:00:00 but from 01:00:00. I thought maybe its because the time is in ap mode, but I havent specified that, here is how I do it:
customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
And the plot at point 0 starts from hour 1:
I would appreciate all help regarding this. How to make the starting point 0 shown as 00:00:00?
I am trying to work on viz module of opencv 3.0 using visual studio 2013 and I used to integrate opencv with it by mentioning library and include directories path. Can any one suggest a way to integrate it without using cmake. I am getting an error saying nvcc is not compatible with visual studio 2013. Please help me soon.
*Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?*
My Solution
int main()
{
vector <float> a;
int count=0;
float k;
int size=100;
count=(size-1)*(size-1);
// take the log of all the values and put them in an array
for(int i=2;i<=size;i++)
for(int j=2;j<=size;j++)
a.push_back(k=i*log(j));
// sort the vector array
sort(a.begin(),a.begin()+count);
int distinct=count;
//check for duplicates, for each duplicate reduce 1 from total no. of elements
for(int i=0;i<count;i++)
if(a[i]==a[i+1])
distinct--;
// Output distinct
cout<<distinct<<endl;
return 0;
}
There are 2 function overloads:
MyClass do_something(MyClass param);
const MyClass& do_something(const MyClass& param);
Then I do:
MyClass c1 {"c1"};
do_something(c1); // I want this to be used by value overload
do_something(c1); // this to be used by reference overload
Is there any special way to explicitly specify that argument is passed by value or by reference?
For move semantic there is std::move() I wonder if there is anything like std::copy() std::ref for my case?
P.S. It's not to be used in real program, just checking out by myself the difference of passing arguments, returning values and their behaviour in different ways and have all functions with the same name:
// pass by value (copy)
MyClass do_something(MyClass param) {
cout << "do_something(MyClass param)" << endl;
param.i = 100;
return param;
}
// !!! Your normal habit when passing an argument to a function should be to pass by const reference. (thinking in c++)
// pass by reference (reference)
const MyClass& do_something(const MyClass& param) { // doesn't allow to modify the object
cout << "do_something(MyClass& param)" << endl;
return param;
}
// pass by move semantic (move)
MyClass&& do_something(MyClass&& param) {
cout << "do_something(MyClass&& param)" << endl;
param.name += "__after_do_something(MyClass&& param)";
param.i = 100;
return move(param);
}
// pass by pointer (reference)
MyClass* do_something(MyClass* const param) { // allows to modify object, but not pointer (address)
cout << "do_something(MyClass* const param)" << endl;
param->i = 100;
// (*param).i = 100; // the same as above
return param;
}
I am working on Android NDK app in which I have to generate a sound. I have written a program in cpp by which I am able to generate a sound. below is my cpp snippet.
#include <dos.h>
#include<iostream.h>
void main()
{
...
sound(1000);
delay(1000);
nosound();
...
}
So, I have written above code in Android JNI, but getting compilation error for dos.h and iostream.h "no such file or directory". Am I missing something here?
The main task is to play an audio sinewave from c++ by giving a call from android using JNI. The frequency of the sine wave has to be passed from the android code.
I am trying to compile my project with cmake, but it's difficult... My project compile with one simple make, but not with cmake. The error is during the link. CMake prefers launch g++ ... -o ... instead of nvcc ... -o .... If I force nvcc, the error is -rdynamic is unknown.
So, it's my cmake file
cmake_minimum_required(VERSION 2.8)
project(LightRays)
find_package(CUDA QUIET REQUIRED)
list(APPEND CUDA_NVCC_FLAGS "-std=c++11;-rdc=true")
file(GLOB_RECURSE
source_file
src/*
include/*)
CUDA_ADD_EXECUTABLE(LightRays ${source_file})
target_link_libraries(LightRays -lSDL -L/opt/cuda/lib64 -lcuda -lcudart)
add_definitions(-std=c++11)
target_link_libraries(LightRays -lSDL -L/opt/cuda/lib64 -lcuda -lcudart)
add_definitions(-std=c++11)
and here errors :
/tmp/tmpxft_00006509_00000000-4_global.cudafe1.stub.c:8: référence indéfinie vers « __cudaRegisterLinkedBinary_41_tmpxft_00006509_00000000_7_global_cpp1_ii_0ad406bb »
CMakeFiles/http://ift.tt/1NpeY9G: dans la fonction « __sti____cudaRegisterAll_40_tmpxft_00006518_00000000_7_tools_cpp1_ii_278b9139() »:
....
Thanks for all and sorry for english...
I used houghLines transformation to detect lines in an image and I draw the lines detected by that on a separate Mat image using cv::line() function. Note that the lines detected by houghLinesP are usually overlapping with each other and high in number. (even if there is 1 line in the image it will detect number of adjacent lines for it)
for (size_t i = 0; i < lines.size(); i++)
{
Vec4i l = lines[i];
line(src, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 255, 0), 10, CV_AA);
}
I wanted to draw the lines in solid green color without any transparency. But in the resulting image I noticed that some lines at the edges are transparent. (or the borders of lines are blurred) Following is a part of my resulting image.
I want to avoid this. I want to have sharp edges for the lines and should not have any transparency. How to do it?
What I want is to have a multiple-line text input, and to be able to count the number of lower-case letters, upper-case letters, periods, commas, spaces, line-breaks, and other characters in the input.
I am trying to use just one string with getline for inputs in a while loop with a running count for each punctuation category.
I just don't know how to actually figure out how many of each character type there are in each line. Given a string, how do I count the number of each type?
Here is my code so far (obviously incomplete):
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int main(){
cout << "This program takes any number of sentences as inputs. " << endl;
cout << "It will count the number of lower-case letters and upper-case letters. " << endl;
cout << "It will also count the number of periods, exclamation marks, spaces, end-lines, etc. " << endl;
cout << " " << endl;
cout << "Please type your text, pressing enter whenever you wish to end a line. " << endl;
cout << "Use the EOF key (CTRL + Z on Windows) when you are finished. " << endl;
string InputString; // This is the string that will be used iteratively, for each line.
int NumberOfLowerCase = 0;
int NumberOfUpperCase = 0;
int NumberOfSpaces = 0; // spaces
int NumberOfTabs = 0; // tabs
int NumberOfPeriods = 0; // periods
int NumberOfCommas = 0; // commas
int NumberOfOtherChars = 0; // other characters
int NumberOfEnters = 0; // end of line, will be incremented each loop
do {
getline(cin, InputString); // input
cout << InputString << endl; // filler just to test the input
NumberOfLowerCase = NumberOfLowerCase + 0 // I don't know what I should be adding
// (obviously not zero, that's just a filler)
} while (!cin.eof() && cin.good());
system("pause");
return 0;
}
The question was inspired by this article: http://ift.tt/1dq3JkT
In short, it discourages us to write tests that break when we change the interface in our functions, forcing us to waste time rewriting each call to match new signature.
If we take above article and guidelines into consideration, it becomes logical to rewrite functions from
void someFunc(int param1, int param2)
to
void someFunc(Object o)
in fact, originally the function may have been called as:
somefunc(o.param1, o.param2);
and now it becomes
somefunc(o);
So, passing an object instead of separate params, gives us some protection for cases where we might need o.param3 for use in function later down the line. But..... does it not contradict the guideline that functions should not receive more information than they need to operate on? I certainly remember reading something like that a couple years back.
If an object has param4 and param5 that this function will never need, then passing the whole object seems incorrect in the light of this guideline...
What is the correct way to think about it? I am only starting to really get into unit testing and stuff like this is kinda confusing to me.
I am implementing a stack using a singly linked list where the Head is at the top of the stack and the Tail is at the bottom of the stack.
I am implementing a pop operation. In order to do this, I must make the head equal to the second node in the linked list. But before I do this, I need to delete the first node in the linked list first. I can do this using delete head->next;.
My question is, if I delete that first node, can I still use it to move on to the next node? Or is it bad practice to use a reference of a node that has had delete called on it. Here is the code I want to use to implement pop.
delete head->next;
head->next = head->next->next;
I am writing a program that implements a uni-directional graph using std::map. I have to search for the key and then copy the vector values corresponding to that key into a new location in the map. The problem is that the key I search for is extracted from yet another location in the map. I understand why I am getting the error as std::copy_n does not copy from vector to string (although it works the other way) but I don't know how to fix this. I am copying a snippet of the code below: The keys to search for are stored in a vector corresponding to key mykey.
for (
vector<string>::iterator itr = mymap.find(mykey)->second.begin()
; itr != mymap.find(mykey)->second.end()
; itr++
)
{
string find_key = "";
// error C2664 :cannot convert parameter 1 from 'std::_Vector_iterator<_Myvec>'
// to 'const std::basic_string<_Elem,_Traits,_Ax> &'
std::copy_n(itr, 1, find_key.begin());
if (mymap.find(find_key) == mymap.end())
cout << "key not found" << endl;
else
mymap[mykey].insert(
mymap.find(find_key)->second.begin()
, mymap.find(find_key)->second.end()
);
}
I have the following code:
#include <iostream>
using namespace std;
int main()
{
int a = 0x80000000;
if(a == 0x80000000)
a = 42;
cout << "Hello World! :: " << a << endl;
return 0;
}
The output is
Hello World! :: 42
so the comparison works. But the compiler tells me
g++ -c -pipe -g -Wall -W -fPIE -I../untitled -I. -I../bin/Qt/5.4/gcc_64/mkspecs/linux-g++ -o main.o ../untitled/main.cpp
../untitled/main.cpp: In function 'int main()':
../untitled/main.cpp:8:13: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
if(a == 0x80000000)
^
So the question is: Why is 0x80000000 an unsigned int? Can I make it signed somehow to get rid of the warning?
As far as I understand, 0x80000000 would be INT_MIN as it's out of range for positive a integer. but why is the compiler assuming, that I want a positive number?
I'm compiling with gcc version 4.8.1 20130909 on linux.
I have the following problems compiling my DLL and I do not devo I'm still newbies in this someone help me
Spanish: Tengo los siguientes problemas al compilar mi DLL y no me devo Sigo siendo novatos en este alguien me ayude
Commands.obj : error LNK2019: unresolved external symbol "public: bool __thiscall SistemaComandos::ACT_GameMaster1(unsigned long)" (?ACT_GameMaster1@SistemaComandos@@QAE_NK@Z) referenced in function "private: void __thiscall SistemaComandos::ComandoGG(int,char *)" (?ComandoGG@SistemaComandos@@AAEXHPAD@Z)
File.CPP:
#include "Stdafx.h"
SistemaComandos ACTComandoToken;
SistemaComandos::SistemaComandos()
{
}
SistemaComandos::~SistemaComandos()
{
}
void SistemaComandos::ComandoGG(int aIndex, char * ACT_String)
{
OBJECTSTRUCT* lpObj = (OBJECTSTRUCT*)OBJECT_POINTER(aIndex);
this->ACT_Ativar = GetPrivateProfileIntA("Staff","Ativar_GG",1,GLplugCommand);
this->ACT_Level = GetPrivateProfileIntA("Staff","Level_GG",1,GLplugCommand);
this->ACT_Dinheiro = GetPrivateProfileIntA("Staff","Zen_GG",1,GLplugCommand);
this->ACT_SomenteGM = GetPrivateProfileIntA("Staff","GM_GG",1,GLplugCommand);
if(this->ACT_Ativar == 0)
{
ACT_Mensagens(lpObj->m_Index,59,0);
return;
}
if(lpObj->Level < this->ACT_Level)
{
ACT_Mensagens(lpObj->m_Index,60,this->ACT_Level);
return;
}
if(lpObj->Money < this->ACT_Dinheiro)
{
ACT_Mensagens(lpObj->m_Index,61,this->ACT_Dinheiro);
return;
}
if(this->ACT_SomenteGM == 1)
{
if(ACT_GameMaster(aIndex) == false)
{
ACT_Mensagens(lpObj->m_Index,62,this->ACT_SomenteGM);
return;
}
}
char Message[255];
sprintf(Message,"%s: %s",lpObj->Name,ACT_String);
StringSendAll(Message,0,0);
}
void SistemaComandos::ACT_ComandoInicio(LPBYTE ACTProtocolo, int aIndex)
{
OBJECTSTRUCT* lpObj = (OBJECTSTRUCT*)OBJECT_POINTER(aIndex);
// Comando GG
GetPrivateProfileString("ACTComandos","String_GG","vazio",GG,64,GLplugCommand);
if(!memicmp(&ACTProtocolo[13],GG,strlen(GG)))
{
this->ComandoGG(aIndex,(char*)ACTProtocolo+13+strlen(GG));
}
}
Files.H:
class SistemaComandos
{
public:
SistemaComandos();
virtual ~SistemaComandos();
int ACT_Ativar;
short ACT_Level;
int ACT_Vip;
int ACT_SomenteGM;
int ACT_Dinheiro;
int ACT_Skin;
int ACT_Inventario;
int ACT_Color;
int Experiencia;
void ACT_ComandoInicio (LPBYTE ACTProtocolo, int aIndex);
bool ACT_GameMaster (DWORD gObjId);
private:
int ACT_Pontos;
short ACT_Index;
short ACT_Id;
short ACT_Levell;
short ACT_Skill;
short ACT_Luck;
short ACT_Addopt;
short ACT_Addoptex;
short ACT_Anciente;
short ACT_Quantidade;
short ACT_Mapa;
short ACT_Cordx;
short ACT_Cordy;
TCHAR Post[64];
TCHAR AddFor[64];
TCHAR AddAgi[64];
TCHAR AddVit[64];
TCHAR AddEne[64];
TCHAR AddCom[64];
TCHAR LimparPk[64];
TCHAR Zen[64];
TCHAR Online[64];
TCHAR Skin[64];
TCHAR DropItemMapa[64];
TCHAR GG[64];
TCHAR ReloadConfig[64];
TCHAR MoverTodos[64];
TCHAR VirarGM[64];
TCHAR VirarBM[64];
TCHAR VirarHE[64];
TCHAR VirarDM[64];
TCHAR VirarLE[64];
TCHAR ComandoEvo[64];
void ComandoPost (int aIndex, char * ACT_String);
void ComandoAdd (int aIndex, LPCSTR ACT_Strin, char pontos);
void ComandoLimparPk (int aIndex, char * ACT_String);
void ComandoZen (int aIndex, char * ACT_String);
void ComandoOnline (int aIndex, char * ACT_String);
void ComandoSkin (int aIndex, char * ACT_String);
void ComandoDropItemMapa (int aIndex, char * ACT_String);
void ComandoGG (int aIndex, char * ACT_String);
void ComandoReloadConfigs (int aIndex, char * ACT_String);
void ComandoMoverTodos (int aIndex, char * ACT_String);
void ComandoTrocarClasse (int aIndex, char * ACT_String, BYTE Tipo);
void ComandoEvo3Classe (int aIndex, char * ACT_String);
};
As you fix it easy and simple
how to implements PHP serialize and unserialize with C++ .I tryed to inclued php source code ,but failed.
i am facing a problem in operator overloading ,when i compile my programe it give me the errors,following is the code :
class box
{
int length;
int width;
int volume;
public:
box():length(50),width(30)
{
}
box& operator++()
{
volume++;
width++;
length++;
}
};
int main()
{
box b1;
cout<<++b1;
}
the error it give is "no match for operator <<" my question is why compiler is giving the error although my syntax seems good.
I am using StereoSGBM to match correspondences to create the disparity map can I create a slider on the window to change the parameters of this algorithm? , note that I am using c++ console application. if yes, HOW ?
I am trying to store a collection of key-value pair in cpp, where key will be a string, as will the value - in my case, a JSON string representing an object.
Then I need to access this json object using Key1 For Example
Key1 = name1 Value1 = {name:"Anil Gautam","age":25}
Key2 = name2 Value2 = **strong text** = {name:"Sharan Gupta","age":26}
I want to access
{name:"Anil Gautam","age":25}
when I input "name1". What Can I possible do to store this kind of data in cpp.
There are so much literature about smart pointers, I have read as much as I could. I just want a simple answer.
I have used raw pointer for my 3D renderer engines, and now I have to share some widgets between renderers, so here smart pointer comes. Please guide me should I update my entire software/library with smart pointer (std::shared_ptr)? What will be the cons in that case? I know the pros, just wanna know are there any cons? and what things are important that I should consider during the transformation from raw pointers to smart pointers? please be specific? Thanks.
The following code compiles fine:
struct A
{
const int a;
virtual void foo() = 0;
};
struct B : A{ };
void A::foo(){ std::cout << "foo" << std::endl; }
The thing is the struct A is an abstract therefore we can't instanciate it. But we can subclass it and
struct A
{
const int a;
virtual void foo() = 0;
};
struct B : A{ };
void A::foo(){ std::cout << "foo" << std::endl; }
int main(int argc, char ** argv)
{
B b;
b.foo(); //error: implement pure-virtual
}
still can't use the A's implementation of foo and I suspect it will never called. So, I have no idea about application of such definition... Yes, it's useful to provide a definition for a virtual destructors, but that's not the case.
Where the definition of pure-virtuals can be used?
For example I've written C++ code to merge three arrays, but here you can see that first I had to merge first two arrays and then merge its resulting array to third array..
while (p < n1 && q < n2) // n1,n2,n3 are sizes of a,b,c respectively
{
if (a[p] < b[q])
{
res[r] = a[p]; // res is array is intermediate merged array
r++;
p++;
}
else
{
res[r] = b[q];
r++;
q++;
}
}
while (q < n2)
{
res[r] = b[q];
r++;
q++;
}
while (p < n1)
{
res[r] = a[p];
r++;
p++;
}
while (s < r && t < n3)
{
if (res[s] < c[t])
{
res2[r2] = res[s]; // res2 is finally merged array
r2++;
s++;
}
else
{
res2[r2] = c[t];
r2++;
t++;
}
}
while (s < r)
{
res2[r2] = res[s];
s++;
r2++;
}
while (t < n3)
{
res2[r2] = c[t];
r2++;
t++;
}
I don't want to use intermediate array in my program.Is there any way I can do it?
Also, Is there any methodology using which we can merge any number of sorted arrays in one go ?
Consider the following code in which we initialize part of D based on another part of D:
struct c {
c() : D{rand(), D[0]} {}
int D[2];
};
int main() {
c C;
assert(C.D[0] == C.D[1]);
}
Is the above program well-defined? Can we safely use one part of the same array to initialize another part of it?
) A program consists of n threads. Each thread works in phases. Each thread begins in phase 1. It is required that all threads complete phase 1 before they can begin phase 2. Likewise, each thread must complete phase 2 before any thread can begin phase 3, and so on. So, the code for each thread has the following structure. for (i = 1; ;i++) { Execute phase i WaitForBarrier(i, threadid); } The function WaitForBarrier ensures that if a thread finishes phase i too quickly then it is blocked. When all threads finish phase i, they are resumed so that they can continue executing phase i+1. Write the function WaitForBarrier(int, int) using semaphores. Explain the correctness of your solution.
I'm using an MPMusicPlayerController to access and play music in an objective C file, but I need to play it in my C++ file using SimpleAudioEngine. Is it possible to select an item with MPMusicPlayerController and use its URL(ipod-library://item/item.m4a?id=456458322781804615) to play the music?
I have a window with extended frame made like this:
But anything drawn in the extended frame has very strange colors (except for white, the only color that stays the same), like this (ignore the messy content in the center and the messy toolbar at the right.
The pink rectangle (0xFFC9FF) was supposed to be 0x8000FF. If I put the DirectX11 content (the center thing) in the extended frame, alpha blending for my FPS counter gets messed up. If I do the same to the right dialog, the same happens.
So how can I do this correctly? I've already tried to draw first to a memory DC and then use BitBlt. I'm using GDI+ (plus CreateCompatibleDC, CreateCompatibleBitmap and other functions to handle the memory DC).
PS: Because you asked, here is WndProc:
LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT ReturnValue;
if (DwmDefWindowProc(hWnd, uMsg, wParam, lParam, &ReturnValue)) return ReturnValue;
switch (uMsg)
{
case WM_CREATE:
{
// ...
RECT rcClient;
GetWindowRect(hWnd, &rcClient);
SetWindowPos(hWnd,
NULL,
rcClient.left, rcClient.top,
rcClient.right - rcClient.left, rcClient.bottom - rcClient.top,
SWP_FRAMECHANGED);
return 0;
}
case WM_ACTIVATE:
{
MARGINS Margins;
Margins.cxLeftWidth = LEFT_BORDER;
Margins.cxRightWidth = RIGHT_BORDER;
Margins.cyTopHeight = TOP_BORDER;
Margins.cyBottomHeight = BOTTOM_BORDER;
if (DwmExtendFrameIntoClientArea(hWnd, &Margins) != S_OK)
{
MessageBox(hWnd, L"Erro ao configurar janela.", NULL, MB_ICONERROR);
PostQuitMessage(WM_QUIT);
}
if (LOWORD(wParam))
{
fActive = true;
}
else
{
fActive = false;
}
InvalidateRect(hWnd, NULL, false);
return 0;
}
case WM_SIZE:
/* ... */
case WM_NCCALCSIZE:
return 0;
case WM_NCHITTEST:
/* ... */
case WM_GETMINMAXINFO:
((LPMINMAXINFO)lParam)->ptMinTrackSize = { 640, 400 };
return 0;
case WM_PAINT:
{
using namespace Gdiplus;
PAINTSTRUCT ps;
HDC hDC = BeginPaint(hWnd, &ps);
RECT rcWindow;
GetWindowRect(hWnd, &rcWindow);
POINT ptSize = { rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top };
HDC hBuffer = CreateCompatibleDC(hDC);
HBITMAP hBitmap = CreateCompatibleBitmap(hDC, ptSize.x, ptSize.y);
SelectObject(hBuffer, hBitmap);
Graphics graphics(hBuffer);
Pen Outline(Color(128, 128, 128));
SolidBrush Selected(Color(128, 0, 255));
Rect Tab1(10, 10, 200, 50);
graphics.FillRectangle(&Selected, Tab1);
graphics.DrawRectangle(&Outline, Tab1);
/* ... */
BitBlt(hDC, 0, 0, ptSize.x, ptSize.y, hBuffer, 0, 0, SRCCOPY);
EndPaint(hWnd, &ps);
return 0;
}
/* ... */
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
I have programming experience in C, and now I want to move on to C++. So, which book, out of Object Oriented Programming in C++ by Robert Lafore and C++ Primer by Stanley B. Lippman should I purchase?
Or, is there any other book, better than these two?
I would love to see a C++ solution as well, so I am tagging c++ in my question (not doing language spam!)
I have a List<List<int>> set of data, with string representation like this (to give the idea!):
{{1,3},{-1,-3},{2,5},{-2,-5},{-3,4},{-5,4},{3,5,-4},{6,-8},{7,-8},{-6,-7,8},{7,9},{-7,-9},{3,8,-10},{-3,-8,-10},{-3,8,10},{3,-8,10},{4,9,-11},{-4,-9,-11},{-4,9,11},{4,-9,11},{10,11},{-1,6},{1,-6},{-2,7},{2,-7}}
I want to check if ,in all present numbers, exist a number or set of numbers which only are in positive form. I mean if in the whole data, there is 3 and -3 I should return false, otherwise I have to add 3 as a number which only is present as positive 3, in to another list. (Same thing for only negative number)
Here is how I am trying to do it:
First, generate a unique set of numbers and remove negatives:
private void GenerateCurrentExistingVariables()
{
_uid = new List<int>();
var all = _cnf.Data.SelectMany(list => list).ToList();
_uid = all.Distinct().ToList(); //make list unique
_uid.Sort(); //sort numbers
_uid.Reverse(); //reverse so highest numbers would evalaute first!
_uid = _uid.Where(i => i >= 0).ToList(); //remove negative numbers
}
Then I do something like this:
in a method, I call the code below:
for (var i = 0; i < _uid.Count; i++)
{
if (ExistOnlyInNegatedForm(_uid[i]))
{
onlyNegatedList.Add(_uid[i]);
}
//perhaps continue
if (ExistOnlyInPositiveForm(_uid[i]))
{
onlyPositiveList.Add(_uid[i]);
}
}
Which in turns calls the methods below:
private bool ExistOnlyInPositiveForm(int id)
{
for (var i = 0; i < _cnf.Data.Count; i++)
{
for (var j = 0; j < _cnf.Data[i].Count; j++)
{
if (_cnf.Data[i][j] == id)
{
return false;
}
}
}
return true;
}
private bool ExistOnlyInNegatedForm(int id)
{
var toCheck = -id;
for (var i = 0; i < _cnf.Data.Count; i++)
{
for (var j = 0; j < _cnf.Data[i].Count; j++)
{
if (_cnf.Data[i][j] == -toCheck)
{
return false;
}
}
}
return true;
}
This is too much code for this simple task and I feel that this is getting slower and slower when data grows larger...please let me know how can I improve this. Also I would like this to be done using LINQ at least for the sake of less lines of code!
I've been profiling a bottleneck in my code (a function shown below) that gets called several million times. I could use tips on increasing the performance. The XXXs numbers were taken from Sleepy.
Compiled with visual studio 2013, /O2 and other typical release settings.
indicies is typically 0 to 20 values, and other parameters are the same size (b.size() == indicies.size() == temps.size() == temps[k].size()).
1: double Object::gradient(const size_t j,
2: const std::vector<double>& b,
3: const std::vector<size_t>& indices,
4: const std::vector<std::vector<double>>& temps) const
5: 23.27s {
6: double sum = 0;
7: 192.16s for (size_t k : indices)
8: 32.05s if (k != j)
9: 219.53s sum += temps[k][j]*b[k];
10:
11: 320.21s return boost::math::isfinite(sum) ? sum : 0;
13: 22.86s }
Any ideas?
Thanks for the tips guys. Here were the results I got from the suggestions:
I found it interesting that switching to cbegin() and cend() had such a large impact. I guess the compiler isn't being as smart as it could there. I'm happy with the bump, but still curious if there's more room here through unrolling or vectorization.