visual c++: convert int into string pointer - visual-c++

how to convert integer into string pointer in visual c++?

Use stringstream
#include <sstream>
stringstream ss;
ss << i;
string s = ss.str();

If you using CString, then you can use Format() method like this:
int val = 489;
CString s;
s.Format("%d", val);

search for atoi / itoa in your favorite documentation. Or try Boost (www.boost.org - library Conversion, lexical_cast).
Both ways are portable across different compilers.

There is a very easy method
int i=4;
String ^ s = Convert::ToString(i);

If you want a textual representation of the pointer address use sprintf.
If you want to treat the numeric value as a pointer to a string use casting like so:
int intValue = ...;
char * charPtr = (char*)intValue;

Take any C and C++ textbook. This simple C code should work in Visual C++ and others C++ compilels and convert 489 into "489":
char result[100];
int num = 489;
sprintf(result, "%d", num);

basic C++
char text[100];
int num=123;
itoa(num,text,10);

This is how I did it in my homework since we were only allowed to use some predetermined libraries. I'm pretty sure it's not considered a "best practice" though ;)
string int2string(int integer) {
string str;
int division = integer;
while (division > 0) {
str = char('0' + (division % 10)) + str;
division = division / 10;
}
return str;
}

I think the easiest one would be:
int i;
String s=i.toString();
// It is about Visual C++

You got homework? a generic one, tested if g++, http://effocore.googlecode.com/svn/trunk/devel/effo/codebase/addons/inl/include/impl/algo_impl.h
:
#ifdef __cplusplus
static inline char *int2a_put(uintptr_t i, char *s)
{
do {
*s++ = '0' + i % 10;
i /= 10;
} while (i);
return s;
}
static inline void int2a_reverse(char *head, char *tail)
{
for (*tail = '\0'; --tail > head; ++head) {
/* exchange */
(*head) ^= (*tail);
(*tail) ^= (*head);
(*head) ^= (*tail);
}
}
template<typename t>
static inline const char *int2a(t i, char *s)
{
char *p;
char *ret = s;
bool f = false;
p = s;
if (i < 0) {
*p++ = '-';
++ s;
/*
* In limits.h, INT_MAX was defined as
* maximum values a `signed int' can hold.
* and LONG_MAX was defined as maximum values
* a `signed long int' can hold.
*/
switch (sizeof(t)) {
case 8:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
ef64_t a = (ef64_t)i;
if (-LLONG_MAX > a) {
i = (t)LLONG_MAX;
f = true;
}
}
break;
case 4:
case 2:
case 1:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
int a = (int)i;
if (-INT_MAX > a) {
i = (t)INT_MAX;
f = true;
}
}
break;
default:
break;
}
if (!f) {
i = -i;
}
}
p = int2a_put((uintptr_t)i, p);
if (f) {
++ *s;
}
int2a_reverse(s, p);
return ret;
}
/*
* No "static" otherwise g++ complains
* "explicit template specialization cannot have a storage class"
*/
template<>
/*static*/ inline
const char *int2a<uintptr_t>(uintptr_t i, char *s)
{
char *p = int2a_put(i, s);
int2a_reverse(s, p);
return s;
}
#else

Related

Find all string permutations of given string in given source string

We are given a pattern string: 'foo' and a source string: 'foobaroofzaqofom' and we need to find all occurrences of word pattern string in any order of letters. So for a given example solution will looks like: ['foo', 'oof', 'ofo'].
I have a solution, but i'm not sure that it is the most efficient one:
Create hash_map of chars of pattern string where each char is a key and each value is a counter of chars in pattern. For a given example it would be {{f: 1}, {o: 2}}
Look through the source string and if found one of the elements from hash_map, than try to find all the rest elements of pattern
If all elements are found than it is our solution, if not going forward
Here is an implementation in c++:
set<string> FindSubstringPermutations(string& s, string& p)
{
set<string> result;
unordered_map<char, int> um;
for (auto ch : p)
{
auto it = um.find(ch);
if (it == um.end())
um.insert({ ch, 1 });
else
um[ch] += 1;
}
for (int i = 0; i < (s.size() - p.size() + 1); ++i)
{
auto it = um.find(s[i]);
if (it != um.end())
{
decltype (um) um_c = um;
um_c[s[i]] -= 1;
for (int t = (i + 1); t < i + p.size(); ++t)
{
auto it = um_c.find(s[t]);
if (it == um_c.end())
break;
else if (it->second == 0)
break;
else
it->second -= 1;
}
int sum = 0;
for (auto c : um_c)
sum += c.second;
if (sum == 0)
result.insert(s.substr(i, p.size()));
}
}
return result;
}
Complexity is near O(n), i don't know how to calculate more precisely.
So the question: is there any efficient solution, because using hash_map is a bit of hacks and i think there may be more efficient solution using simple arrays and flags of found elements.
You could use a order-invariant hash-algorithm that works with a sliding window to optimize things a bit.
An example for such a hash-algorithm could be
int hash(string s){
int result = 0;
for(int i = 0; i < s.length(); i++)
result += s[i];
return result;
}
This algorithm is a bit over-simplistic and is rather horrible in all points except performance (i.e. distribution and number of possible hash-values), but that isn't too hard to change.
The advantage with such a hash-algorithm would be:
hash("abc") == hash("acb") == hash("bac") == ...
and using a sliding-window with this algorithm is pretty simple:
string s = "abcd";
hash(s.substring(0, 3)) + 'd' - 'a' == hash(s.substring(1, 3));
These two properties of such hashing approaches allow us to do something like this:
int hash(string s){
return sum(s.chars);
}
int slideHash(int oldHash, char slideOut, char slideIn){
return oldHash - slideOut + slideIn;
}
int findPermuted(string s, string pattern){
int patternHash = hash(pattern);
int slidingHash = hash(s.substring(0, pattern.length()));
if(patternHash == slidingHash && isPermutation(pattern, s.substring(0, pattern.length())
return 0;
for(int i = 0; i < s.length() - pattern.length(); i++){
slidingHash = slideHash(slidingHash, s[i], s[i + pattern.length()]);
if(patternHash == slidingHash)
if(isPermutation(pattern, s.substring(i + 1, pattern.length())
return i + 1;
}
return -1;
}
This is basically an altered version of the Rabin-Karp-algorithm that works for permuted strings. The main-advantage of this approach is that less strings actually have to be compared, which brings quite a bit of an advantage. This especially applies here, since the comparison (checking if a string is a permutation of another string) is quite expensive itself already.
NOTE:
The above code is only supposed as a demonstration of an idea. It's aimed at being easy to understand rather than performance and shouldn't be directly used.
EDIT:
The above "implementation" of an order-invariant rolling hash algorithm shouldn't be used, since it performs extremely poor in terms of data-distribution. Of course there are obviously a few problems with this kind of hash: the only thing from which the hash can be generated is the actual value of the characters (no indices!), which need to be accumulated using a reversible operation.
A better approach would be to map each character to a prime (don't use 2!!!). Since all operations are modulo 2^(8 * sizeof(hashtype)) (integer overflow), we need to generate a table of the multiplicative inverses modulo 2^(8 * sizeof(hashtype)) for all used primes. I won't cover generating these tables, as there's plenty of resources available on that topic here already.
The final hash would then look like this:
map<char, int> primes = generatePrimTable();
map<int, int> inverse = generateMultiplicativeInverses(primes);
unsigned int hash(string s){
unsigned int hash = 1;
for(int i = 0; i < s.length(); i++)
hash *= primes[s[i]];
return hash;
}
unsigned int slideHash(unsigned int oldHash, char slideOut, char slideIn){
return oldHash * inverse[primes[slideOut]] * primes[slideIn];
}
Keep in mind that this solution works with unsigned integers.
Typical rolling hashfunction for anagrams
using product of primes
This will only work for relatively short patterns
The hashvalues for allmost all normal words will fit into a 64 bit value without overflow.
Based on this anagram matcher
/* braek; */
/* 'foobaroofzaqofom' */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef unsigned long long HashVal;
static HashVal hashchar (unsigned char ch);
static HashVal hashmem (void *ptr, size_t len);
unsigned char primes26[] =
{ 5,71,79,19,2,83,31,43,11,53,37,23,41,3,13,73,101,17,29,7,59,47,61,97,89,67, };
/*********************************************/
static HashVal hashchar (unsigned char ch)
{
HashVal val=1;
if (ch >= 'A' && ch <= 'Z' ) val = primes26[ ch - 'A'];
else if (ch >= 'a' && ch <= 'z' ) val = primes26[ ch - 'a'];
return val;
}
static HashVal hashmem (void *ptr, size_t len)
{
size_t idx;
unsigned char *str = ptr;
HashVal val=1;
if (!len) return 0;
for (idx = 0; idx < len; idx++) {
val *= hashchar ( str[idx] );
}
return val;
}
/*********************************************/
unsigned char buff [4096];
int main (int argc, char **argv)
{
size_t patlen,len,pos,rotor;
int ch;
HashVal patval;
HashVal rothash=1;
patlen = strlen(argv[1]);
patval = hashmem( argv[1], patlen);
// fprintf(stderr, "Pat=%s, len=%zu, Hash=%llx\n", argv[1], patlen, patval);
for (rotor=pos=len =0; ; len++) {
ch=getc(stdin);
if (ch == EOF) break;
if (ch < 'A' || ch > 'z') { pos = 0; rothash = 1; continue; }
if (ch > 'Z' && ch < 'a') { pos = 0; rothash = 1; continue; }
/* remove old char from rolling hash */
if (pos >= patlen) { rothash /= hashchar(buff[rotor]); }
/* add new char to rolling hash */
buff[rotor] = ch;
rothash *= hashchar(buff[rotor]);
// fprintf(stderr, "%zu: [rot=%zu]pos=%zu, Hash=%llx\n", len, rotor, pos, rothash);
rotor = (rotor+1) % patlen;
/* matched enough characters ? */
if (++pos < patlen) continue;
/* correct hash value ? */
if (rothash != patval) continue;
fprintf(stdout, "Pos=%zu\n", len);
}
return 0;
}
Output/result:
$ ./a.out foo < anascan.c
Pos=21
Pos=27
Pos=33
Update. For people who don't like product of primes, here is a taxinumber sum of cubes (+ additional histogram check) implementation. This is also supposed to be 8-bit clean. Note the cubes are not necessary; it wotks equally well with squares. Or just the sum. (the final histogram check will have some more work todo)
/* braek; */
/* 'foobaroofzaqofom' */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef unsigned long long HashVal;
static HashVal hashchar (unsigned char ch);
static HashVal hashmem (void *ptr, size_t len);
/*********************************************/
static HashVal hashchar (unsigned char ch)
{
HashVal val=1+ch;
return val*val*val;
}
static HashVal hashmem (void *ptr, size_t len)
{
size_t idx;
unsigned char *str = ptr;
HashVal val=1;
if (!len) return 0;
for (idx = 0; idx < len; idx++) {
val += hashchar ( str[idx] );
}
return val;
}
/*********************************************/
int main (int argc, char **argv)
{
size_t patlen,len,rotor;
int ch;
HashVal patval;
HashVal rothash=1;
unsigned char *patstr;
unsigned pathist[256] = {0};
unsigned rothist[256] = {0};
unsigned char cycbuff[1024];
patstr = (unsigned char*) argv[1];
patlen = strlen((const char*) patstr);
patval = hashmem( patstr, patlen);
for(rotor=0; rotor < patlen; rotor++) {
pathist [ patstr[rotor] ] += 1;
}
fprintf(stderr, "Pat=%s, len=%zu, Hash=%llx\n", argv[1], patlen, patval);
for (rotor=len =0; ; len++) {
ch=getc(stdin);
if (ch == EOF) break;
/* remove old char from rolling hash */
if (len >= patlen) {
rothash -= hashchar(cycbuff[rotor]);
rothist [ cycbuff[rotor] ] -= 1;
}
/* add new char to rolling hash */
cycbuff[rotor] = ch;
rothash += hashchar(cycbuff[rotor]);
rothist [ cycbuff[rotor] ] += 1;
// fprintf(stderr, "%zu: [rot=%zu], Hash=%llx\n", len, rotor, rothash);
rotor = (rotor+1) % patlen;
/* matched enough characters ? */
if (len < patlen) continue;
/* correct hash value ? */
if (rothash != patval) continue;
/* correct histogram? */
if (memcmp(rothist,pathist, sizeof pathist)) continue;
fprintf(stdout, "Pos=%zu\n", len-patlen);
}
return 0;
}

Is there a Lua string replace() function for faster replacements than gsub()?

I see a list of Lua string functions and I see the .gsub(), for global search and replace: http://www.gammon.com.au/scripts/doc.php?general=lua_string
All lua string functions :
static const luaL_Reg strlib[] = {
{"byte", str_byte},
{"char", str_char},
{"dump", str_dump},
{"find", str_find},
{"format", str_format},
{"gfind", gfind_nodef},
{"gmatch", gmatch},
{"gsub", str_gsub},
{"len", str_len},
{"lower", str_lower},
{"match", str_match},
{"rep", str_rep},
{"reverse", str_reverse},
{"sub", str_sub},
{"upper", str_upper},
{NULL, NULL}
};
Why is there no simple, fast, litteral (non-regex) string replace function?
Is .gsub() so efficient that there is no benefit?
I found this written in 2006 but it does not seem like it's included: http://lua-users.org/wiki/StringReplace
This is likely because gsub is capable of doing exactly what a replace function would do, and Lua's design goals include that of a small, generally uncomplicated standard library. There's no need for a redundancy like this to be baked right into the language.
As an outside example, the Ruby programming language provides both String#gsub and String#replace in its standard library. Ruby is a much, much larger language out of the box because of decisions like this.
However, Lua prides itself on being a very easy language to extend. The link you've shown shows how to bake the function into the standard library when compiling Lua as a whole. You could also piece it together to create a module.
Quickly patching together the parts we need results in (note we need the lmemfind function from lstrlib.c):
#include <lua.h>
#include <lauxlib.h>
#include <string.h>
static const char *lmemfind
(const char *s1, size_t l1, const char *s2, size_t l2) {
if (l2 == 0)
return s1; /* empty strings are everywhere */
else if (l2 > l1)
return NULL; /* avoids a negative 'l1' */
const char *init; /* to search for a '*s2' inside 's1' */
l2--; /* 1st char will be checked by 'memchr' */
l1 = l1-l2; /* 's2' cannot be found after that */
while (l1 > 0 && (init = (const char *) memchr(s1, *s2, l1)) != NULL) {
init++; /* 1st char is already checked */
if (memcmp(init, s2+1, l2) == 0)
return init-1;
else { /* correct 'l1' and 's1' to try again */
l1 -= init-s1;
s1 = init;
}
}
return NULL; /* not found */
}
static int str_replace(lua_State *L) {
size_t l1, l2, l3;
const char *src = luaL_checklstring(L, 1, &l1);
const char *p = luaL_checklstring(L, 2, &l2);
const char *p2 = luaL_checklstring(L, 3, &l3);
const char *s2;
int n = 0;
int init = 0;
luaL_Buffer b;
luaL_buffinit(L, &b);
while (1) {
s2 = lmemfind(src+init, l1-init, p, l2);
if (s2) {
luaL_addlstring(&b, src+init, s2-(src+init));
luaL_addlstring(&b, p2, l3);
init = init + (s2-(src+init)) + l2;
n++;
} else {
luaL_addlstring(&b, src+init, l1-init);
break;
}
}
luaL_pushresult(&b);
lua_pushnumber(L, (lua_Number) n); /* number of substitutions */
return 2;
}
int luaopen_strrep (lua_State *L) {
lua_pushcfunction(L, str_replace);
return 1;
}
We can compile this into a shared object with the proper linkage (cc -shared, cc -bundle, etc...), and load it into Lua like any other module with require.
local replace = require 'strrep'
print(replace('hello world', 'hello', 'yellow')) -- yellow world, 1.0
This answer is a formalized reconstruction of the comments above.

visual c++ - "function already has a body"

Here is my declaration in question, I even use include guards:
Edit: I'm including the entire header if this will help answer any additional
questions one might have.
#ifndef STRING_H
#define STRING_H
#include<iostream>
class String
{
public:
String(const char * s = "");
String(const String & s);
String operator = (const String & s);
char & operator [] (int index);
int size();
String reverse();
int indexOf(char c);
int indexOf(String pattern);
bool operator == (String s);
bool operator != (String s);
bool operator > (String s);
bool operator < (String s);
bool operator >= (String s);
bool operator <= (String s);
String operator + (String s);
String operator += (String s);
void print(std::ostream & out);
void read(std::istream & in);
static int strLen(const String &s);
static String strCpy(const String &s, int length);
static String strDup(const String &s);
static bool strCmp(const String &s, const String &t);
~String();
private:
bool inBounds(int i)
{
return i >= 0 && i < len;
}
char * buf;
int len;
};
#endif
And here is my definition:(starting form line 183)
String String::operator = (const String & s)
{
String t(s);
return t;
}
And I keep getting this error:
>c:\users\omive_000\documents\visual studio 2013\projects\string\string\string.h(183): error C2084: function 'String String::operator =(const String &)' already has a body
1> c:\users\omive_000\documents\visual studio 2013\projects\string\string\string.h(11) : see previous definition of '='
can anyone offer me an explanation as to why this error occurs?
Definitions normally don't belong into header files.
You can declare and define your function inline, inside your include guards
You can use a cpp file
That said, your code looks fishy. It does not do what it seems to do. There is no assignment to this or it's variables happening. But that's a bug and not a compiler error.

Overloading "*" Operator for custom SmartPointer

I am trying to directly access integer from a pointer class, by overloading * operator, but it seems VC++ 10 is not allowing it. Kindly help:
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int MAX7 = 10;
struct node{
int value;
node *next;
};
struct node *head = NULL;
struct node *current = NULL;
int count = 0;
class SmartPointer{
public:
SmartPointer(){
}
int push(int i){
if(count == MAX7) return 0;
if(head == NULL){
head = new node();
current = head;
head -> next = NULL;
head -> value = i;
count = 1;
}
else{
struct node *ptr = head;
while(ptr->next != NULL) ptr = ptr->next;
ptr->next = new node;
ptr = ptr->next;
ptr->next = NULL;
ptr->value = i;
count++;
}
return 1;
}
void Display(){
node *ptr = head;
while(ptr != NULL){
cout << ptr->value << "(" << ptr << ")";
if( ptr == current )
cout << "*";
cout << ", ";
ptr = ptr->next;
}
}
int operator *(){
if(current == NULL) return -1;
struct node *ptr = current;
return ptr->value;
}
};
int main(){
SmartPointer *sp;
sp = new SmartPointer();
sp->push(99);
for(int i=100; i<120; i++){
if(sp->push(i))
cout << "\nPushing ("<<i<<"): Successful!";
else
cout << "\nPushing ("<<i<<"): Failed!";
}
cout << "\n";
sp->Display();
int i = *sp;
getch();
return 0;
}
Error#
1>test7.cpp(71): error C2440: 'initializing' : cannot convert from 'SmartPointer' to 'int'
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
sp is not a smart pointer - it's a plain old dumb pointer to SmartPointer class. *sp uses built-in dereference operator, producing an lvalue of SmartPointer type. It does not call SmartPointer::operator*() - for that, you need to write **sp (two stars).
It's not at all clear why you want to allocate SmartPointer instance on the heap. That's an unusual thing to want to do (also too, you leak it). I'm pretty sure you would be better off with
SmartPointer sp;
sp.push(99);
and so on.
short answer:
int i = **sp;
You should not allocate objects with new. Your code looks like java. In C++, you must delete everything you allocate with new. In C++ you can write:
SmartPointer sp;
sp.push(99);
int i = *sp;

Memory allocation of struct in C++

My struct is as follows:
typedef struct KeypointSt {
float row, col;
float scale, ori;
unsigned char *descrip; /* Vector of descriptor values */
struct KeypointSt *next;
} *Keypoint;
The following is a part of a code in C. How can I translate it to C++, considering allocation and de-allocation of heap.
Keypoint k, keys = NULL;
for (i = 0; i < num; i++) {
/* Allocate memory for the keypoint. */
k = (Keypoint) malloc(sizeof(struct KeypointSt));
k->next = keys;
keys = k;
k->descrip = malloc(len);
for (j = 0; j < len; j++) {
k->descrip[j] = (unsigned char) val;
}
}
One possible way of converting to C++ is:
#include <cstring> // memset()
typedef struct KeypointSt
{
float row, col;
float scale, ori;
size_t len;
unsigned char *descrip; /* Vector of descriptor values */
KeypointSt *next;
KeypointSt(int p_len, int p_val) : row(0.0), col(0.0), scale(0.0),
ori(0.0), len(p_len),
descrip(new unsigned char[len]), next(0)
{ memset(descrip, len, p_val); }
~KeypointSt() { delete descrip; }
} *Keypoint;
extern KeypointSt *init_keypoints(size_t num, size_t len, unsigned char val);
extern void free_keypoints(KeypointSt *list);
KeypointSt *init_keypoints(size_t num, size_t len, unsigned char val)
{
KeypointSt *keys = NULL;
for (size_t i = 0; i < num; i++)
{
/* Allocate memory for the keypoint. */
KeypointSt *k = new KeypointSt(len, val);
k->next = keys;
keys = k;
}
return keys;
}
void free_keypoints(KeypointSt *list)
{
while (list != 0)
{
KeypointSt *next = list->next;
delete list;
list = next;
}
}
int main(void)
{
KeypointSt *keys = init_keypoints(4, 5, 6);
free_keypoints(keys);
return 0;
}
The only reason I've kept the typedef in place is because you have existing code; the C++ code would be better using KeypointSt * everywhere — or renaming the structure tag to Keypoint and using Keypoint * in place of your original Keypoint. I don't like non-opaque types where the typedef conceals a pointer. If I see a declaration XYZ xyz;, and it is a structure or class type, I expect to use xyz.pqr and not xyz->pqr.
We can debate code layout of the constructor code, the absence of a default constructor (no arrays), and the absence of a copy constructor and an assignment operator (both needed because of the allocation for descrip). The code of init_keypoints() is not exception safe; a memory allocation failure will leak memory. Fixing that is left as an exercise (it isn't very hard, I think, but I don't claim exception-handling expertise). I've not attempted to consider any extra requirements imposed by C++11. Simply translating from C to C++ is 'easy' until you look at the extra demands that C++ makes — demands that make your life easier in the long run, but at a short-term cost in pain.

Resources