Вы можете попробовать работать с свойствами патчей contour
: увеличить linewidth
края патча: значение по умолчанию равно 0.5: a linewidth
из 1 или 1.5 должно быть достаточно.
Точно так же вы можете установить свойства лавелей, сгенерированных clabel
: вы можете установить font size
и font weight
, чтобы сделать их более видимыми. Также вы можете установить количество добавляемых меток, указав свойство labelspacing
.
Интересным вариантом может быть также установка вручную меток вручную: это можно сделать, указав свойство manaul
в clabel
.
Ниже вы найдете пример, основанный на поверхности peaks
:
[x,y,z]=peaks
surf(x,y,z);
shading interp
hold on
[c,h] = contour3(x,y,z,[-10:1:10]);
set(h(:),'linewidth',1,'edgecolor','k')
clabel(c,h,[-10:1:10],'fontsize',9,'fontweight','bold','rotation',0,'labelspacing',99);
% clabel(c,h,'manual','fontsize',9,'fontweight','bold','rotation',0);
Надеюсь, что это поможет.
use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
the following example produces -65538
as its result:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string
So, the simplest answer for newer code would probably look like this:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).
It appears that since lexical_cast<>
is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast
and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.
Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
which you can use like this:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
Попробуйте это. Это решение немного опасно. Нет никаких проверок. Строка должна только иметь шестнадцатеричные значения, и длина строки должна соответствовать размеру шрифта возврата. Но никакая потребность в дополнительных заголовках.
char hextob(char ch)
{
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
return 0;
}
template<typename T>
T hextot(char* hex)
{
T value = 0;
for (size_t i = 0; i < sizeof(T)*2; ++i)
value |= hextob(hex[i]) << 4*(sizeof(T)-i+1);
return value;
};
Использование:
int main()
{
char str[4] = {'f','f','f','f'};
std::cout << hextot<int16_t>(str) << "\n";
}
Примечание: длина строки должна быть делимой 2
Для метода, который работает как с C, так и с C ++, вы можете рассмотреть возможность использования стандартной библиотечной функции strtol ().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
Рабочий пример с strtoul
будет:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "fffefffe";
char * p;
long n = strtoul( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
strtol
преобразует строку
в long
. На моем компьютере numeric_limits
дает 0x7fffffff
. Очевидно, что 0xfffefffe
больше, чем 0x7fffffff
. Таким образом, strtol
возвращает MAX_LONG
вместо желаемого значения. strtoul
преобразует строку
в unsigned long
, поэтому в этом случае нет переполнения.
Хорошо, strtol
рассматривает входную строку не как 32-битное целое число со знаком перед преобразованием. Забавный пример с strtol
:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "-0x10002";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
Приведенный выше код печатает -65538
в консоли.
Сегодня у меня была такая же проблема, вот как я решил ее, чтобы сохранить lexical_cast <>
typedef unsigned int uint32;
typedef signed int int32;
class uint32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator uint32() const { return value; }
friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
{
in >> std::hex >> outValue.value;
}
};
class int32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator int32() const { return static_cast<int32>( value ); }
friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
{
in >> std::hex >> outvalue.value;
}
};
uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );
int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...
(Нашел эту страницу, когда искал менее отстойный способ: -)
Ура, А.
Похоже, ваш код противоречит тому, что вы описали в тексте. Если T
- тип итератора, то результат итератора dereference (как вы сказали в тексте) не будет иметь тип T *
(как вы, кажется, верите в код). T *
- это совершенно противоположная вещь: это то, что вы получили бы, если бы вы взяли адрес вашего итератора, а не обособили его.
На самом деле, нет пути выражать «тип без ссылок» с помощью основных языковых функций C++ (может быть, decltype
сделает это в будущем, как в decltype (* T ())
). Единственный способ описать результат отмены привязки типа T
- использовать библиотечное решение: итераторные черты, как объяснил Йоханнес в своём ответе.
Хотя это старый поток, я решил поделиться своим решением ошибки «Can 't rename...»:
Энди Бьюкенен, насколько я придерживаюсь C++, мне понравился ваш, но у меня есть несколько режимов:
template <typename ElemT>
struct HexTo {
ElemT value;
operator ElemT() const {return value;}
friend std::istream& operator>>(std::istream& in, HexTo& out) {
in >> std::hex >> out.value;
return in;
}
};
Используется как
uint32_t value = boost::lexical_cast<HexTo<uint32_t> >("0x2a");
Таким образом, вам не нужен один impl на тип int.