Unable to understand the boost::mutex error C++ - multithreading

I am new to multithreading and I have used the thread pool mechanism to synchronize interactions amongst two classes.
While compiling i am unable to understand the error.
The classes are as below:
InstrumentProcessor.h
1 #ifndef INSTRUMENTPROCESSOR_H
2 #define INSTRUMENTPROCESSOR_H
3
4 #include <boost/thread/thread.hpp>
5 #include <boost/thread/mutex.hpp>
6 #include <boost/algorithm/string.hpp>
7 #include <boost/lexical_cast.hpp>
8 #include "Semaphore.h"
9 #include "Instrument.h"
10 #include <queue>
11 #include <string>
12 #include <vector>
13
14
15 class InstrumentProcessor
16 {
17 public:
18 InstrumentProcessor(unsigned int const numThreads);
19 ~InstrumentProcessor();
20 bool Start();
21 bool Stop();
22 void AddLine(const std::string& LineRead); // Producer
23
24 private:
25 void Process(); // Worker Function
26 void ProcessLine(std::string& line); // Consumer
27
28 private:
29 unsigned int const numThreads_;
30 boost::mutex ProcessorMutex_;
31 boost::thread_group ProcessorGroup_;
32 Semaphore taskCount_;
33 std::queue<std::string> Line_;
34 bool stop_;
35 std::vector<std::string> elements_;
36 std::vector<Instrument> Instruments_;
37 };
38
39 #endif /* INSTRUMENTPROCESSOR_H */
InstrumentProcessor.cpp
1 #include "InstrumentProcessor.h"
2
3 InstrumentProcessor::InstrumentProcessor(unsigned int const numThreads)
4 : numThreads_(numThreads), stop_(false)
5 {
6 Instruments_.reserve(25);
7 }
8
9 InstrumentProcessor::~InstrumentProcessor()
10 {
11
12 }
13
14 bool InstrumentProcessor::Start()
15 {
16 std::cout << "\nParallel Processing Started ...." << std::endl;
17 for(unsigned int i=0; i<numThreads_; i++)
18 {
19 ProcessorGroup_.create_thread(boost::bind(&InstrumentProcessor ::Process, this));
20 }
21
22 return true;
23 }
24
25 bool InstrumentProcessor::Stop()
26 {
27 stop_ = true;
28 ProcessorGroup_.join_all();
29 std::cout << "\n Parallel Processing Stopped ...." << std::endl;
30 return stop_;
31 }
32
33
34 void InstrumentProcessor::Process()
35 {
36 while(!stop_)
37 {
38 --taskCount_;
39 std::string currentLine;
40 {
41 boost::mutex::scoped_lock lock(ProcessorMutex_);
42 currentLine = Line_.front();
43 Line_.pop();
44 }
45 ProcessLine(currentLine);
46 }
47 }
48
49 void InstrumentProcessor::AddLine(const std::string& LineRead)
50 {
51 boost::mutex::scoped_lock lock(ProcessorMutex_);
52 Line_.push(LineRead);
53 ++taskCount_;
54 }
55
56 void InstrumentProcessor::ProcessLine(std::string& line)
57 {
58 boost::algorithm::split(elements_, line, boost::is_any_of("\t "), boos t::token_compress_on);
59 for(unsigned int i=1; i<elements_.size(); i++)
60 {
61 if (elements_[i].compare("nan") == 0)
62 continue;
63 else
64 {
65 double data = boost::lexical_cast<double>(elements_[i] );
66 Instruments_[i-1].CleanData(data); // This function makes a call to the Insrument Class member function
67 }
68 }
69 }
Instrument.h
1 #ifndef INSTRUMENT_H
2 #define INSTRUMENT_H
3
4 #include <iostream>
5 #include <boost/thread/mutex.hpp>
6 #include <cmath>
7
8 class Instrument
9 {
10 public:
11 Instrument();
12 ~Instrument();
13 bool PopulateData(double& data);
14 bool CleanData(double& data);
15 bool PrintData();
16
17 private:
18 bool getMeanAndStandardDeviation();
19
20 private:
21 double data_;
22 int N_;
23 double Mean_;
24 double M2_;
25 double stdDev_;
26 double InitialValue_;
27 bool Init_;
28 boost::mutex InstrumentMutex_;
29 };
30
31 #endif /* INSTRUMENT_H */
Instrument.cpp
1 #include "Instrument.h"
2
3 Instrument::Instrument()
4 : Init_(false), data_(0.0), Mean_(0.0), stdDev_(0.0), InitialValue_(0.0), N_(0 ), M2_(0.0)
5 {
6
7 }
8
9 Instrument::~Instrument()
10 {
11
12 }
13
14 bool Instrument::PopulateData(double& data)
15 {
16 data_ = data;
17 if(!Init_)
18 {
19 InitialValue_ = data_;
20 Init_ = true;
21 std::cout << "The initial value is: " << InitialValue_ << std: :endl;
22 }
23 return true;
24 }
25
26 /* Cleaning Part 2:
27 * Each data point will be represented as the % change from the initial value.
28 * This will then be added by 101 so as to get uniform positive value with the
29 * origin of the data shifted to init_origin + 101
30 */
31
32 bool Instrument::CleanData(double& data)
33 {
34
35 std::cout << "\nData begin inserted: " << data << std::endl;
36 boost::mutex::scoped_lock lock(InstrumentMutex_);
37 PopulateData(data);
38 data_ = ((data_-InitialValue_)/InitialValue_)*100;
39 data_ += 101;
40 getMeanAndStandardDeviation();
41 return true;
42 }
43
44 // Welford recurrence relation for tick based mean and standard deviation calc ulation
45 bool Instrument::getMeanAndStandardDeviation()
46 {
47 ++N_;
48 double delta = data_ - Mean_;
49 Mean_ += delta/N_;
50 M2_ += delta*(data_ - Mean_);
51
52 if(N_ >= 2)
53 {
54 double variance = M2_/(N_-1);
55 stdDev_ = std::sqrt(variance);
56 }
57 return true;
58 }
59
60 bool Instrument::PrintData()
61 {
62 std::cout << "\nMean: " << Mean_ << "Std Dev: " << stdDev_ << std::end l;
63 return true;
64 }
I am compiling the above with the following compilation line:
g++ -std=c++11 -I /usr/lib/x86_64-linux-gnu -lboost_thread -c InstrumentProcessor.cpp
which yields in the below error.
In file included from /usr/include/c++/4.8/memory:64:0,
from /usr/include/boost/config/no_tr1/memory.hpp:21,
from /usr/include/boost/smart_ptr/shared_ptr.hpp:27,
from /usr/include/boost/shared_ptr.hpp:17,
from /usr/include/boost/date_time/time_clock.hpp:17,
from /usr/include/boost/thread/thread_time.hpp:9,
from /usr/include/boost/thread/lock_types.hpp:18,
from /usr/include/boost/thread/pthread/thread_data.hpp:12,
from /usr/include/boost/thread/thread_only.hpp:17,
from /usr/include/boost/thread/thread.hpp:12,
from InstrumentProcessor.h:4,
from InstrumentProcessor.cpp:1:
/usr/include/c++/4.8/bits/stl_construct.h: In instantiation of ‘void std::_Construct(_T1*, _Args&& ...) [with _T1 = Instrument; _Args = {Instrument}]’:
/usr/include/c++/4.8/bits/stl_uninitialized.h:75:53: required from ‘static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*; bool _TrivialValueTypes = false]’
/usr/include/c++/4.8/bits/stl_uninitialized.h:117:41: required from ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*]’
/usr/include/c++/4.8/bits/stl_uninitialized.h:258:63: required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*; _Tp = Instrument]’
/usr/include/c++/4.8/bits/stl_vector.h:1142:29: required from ‘std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = std::move_iterator<Instrument*>; _Tp = Instrument; _Alloc = std::allocator<Instrument>; std::vector<_Tp, _Alloc>::pointer = Instrument*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
/usr/include/c++/4.8/bits/vector.tcc:75:70: required from ‘void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = Instrument; _Alloc = std::allocator<Instrument>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
InstrumentProcessor.cpp:6:25: required from here
/usr/include/c++/4.8/bits/stl_construct.h:75:7: error: use of deleted function ‘Instrument::Instrument(const Instrument&)’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^
In file included from InstrumentProcessor.h:9:0,
from InstrumentProcessor.cpp:1:
Instrument.h:8:7: note: ‘Instrument::Instrument(const Instrument&)’ is implicitly deleted because the default definition would be ill-formed:
class Instrument
^
Instrument.h:8:7: error: use of deleted function ‘boost::mutex::mutex(const boost::mutex&)’
In file included from /usr/include/boost/thread/lock_guard.hpp:11:0,
from /usr/include/boost/thread/pthread/thread_data.hpp:11,
from /usr/include/boost/thread/thread_only.hpp:17,
from /usr/include/boost/thread/thread.hpp:12,
from InstrumentProcessor.h:4,
from InstrumentProcessor.cpp:1:
/usr/include/boost/thread/pthread/mutex.hpp:96:9: error: declared here
BOOST_THREAD_NO_COPYABLE(mutex)
^
Any help on this will be appreciated.

Implementation of method vector::reserve() requires either move-constructor or copy-constructor from Instrument class.
But both of these constructors may not generated for the class automatically, because its member InstrumentMutex_ is neither copiable nor movable (mutexes can neither be copied nor moved).
You need to declare move-constructor for Instrument class manually for possibility to use it in vector operations. Becauase of mutex member, this won't be true move-constructor (mutex cannot be moved), but simple initializing of mutex is sufficient for given usage.
Alternatively, instead of calling .reserve() method after creating the vector _Instruments, you may initialize this vector with precise size:
InstrumentProcessor::InstrumentProcessor(unsigned int const numThreads)
: numThreads_(numThreads), stop_(false), _Instruments(25)
{
}
This initialization requires only default constructor from Instrument class, which is already declared.
Sized vector constructor differs from .reserve() in that all vector's elements are created (as opposite to allocated), which may be not suitable for your case. But if creation of all elements is OK, then this initialization should be preffered for previous one, because it avoids definition of move-constructor without well-defined semantic (mutex member are not moved but recreated).

Related

Who did do a mistake with assignments?

With Qt 6.3.1 and MSVC 2019 (16.11.16) the following code crashes in assignment operator:
#include <QHash>
void fillHash( QHash< int, QString > & hash )
{
const auto str = QStringLiteral( "abc" );
for( qsizetype i = 0; i < 99; i += 3 )
hash[ i ] = hash[ i + 1 ] = hash[ i + 2 ] = str;
}
int main()
{
QHash<int, QString> h;
fillHash(h);
return 0;
}
It crashes with the following stack:
1 std::_Atomic_integral<int,4>::operator++ atomic 1587 0x7ff953ee7279
2 QAtomicOps<int>::ref<int> qatomic_cxx11.h 281 0x7ff953ee3c74
3 QBasicAtomicInteger<int>::ref qbasicatomic.h 101 0x7ff953eed687
4 QArrayData::ref qarraydata.h 88 0x7ff953eed6b7
5 QArrayDataPointer<char16_t>::ref qarraydatapointer.h 325 0x7ff953eed652
6 QArrayDataPointer<char16_t>::QArrayDataPointer<char16_t> qarraydatapointer.h 72 0x7ff953ee40cd
7 QArrayDataPointer<char16_t>::operator= qarraydatapointer.h 93 0x7ff9541ca864
8 QString::operator= qstring.cpp 2825 0x7ff95422d891
9 fillHash main.cpp 9 0x7ff67d9c2d03
10 main main.cpp 18 0x7ff67d9c2dcc
11 invoke_main exe_common.inl 79 0x7ff67d9ca109
12 __scrt_common_main_seh exe_common.inl 288 0x7ff67d9c9fee
13 __scrt_common_main exe_common.inl 331 0x7ff67d9c9eae
14 mainCRTStartup exe_main.cpp 17 0x7ff67d9ca19e
15 BaseThreadInitThunk KERNEL32 0x7ff9b38c7034
16 RtlUserThreadStart ntdll 0x7ff9b4e62651
What's wrong?

Send array to function in BACI (C--)

I want to send an array to a function then print all of the elements. I have an error.
.LST file is:
BACI System: C-- to PCODE Compiler, 16:59 27 Oct 2005
Source file: 1.cm Fri Nov 01 03:16:20 2019
line pc
1 0
2 0
3 0
4 0 void Print(int a[])
Error near '[', line 4 of file 1.cm:
** syntax error
Because of 1 error the PCODE file will not execute
Baci reference is:
http://inside.mines.edu/~tcamp/baci/baci_index.html
C:\badosxe> bacc 1.cm Error near '[', line 4 of file 1.cm: ** syntax error>>Because of 1 error the PCODE file will not execute Pcode and tables are stored in 1.pco Compilation listing is stored in 1.lst
void Print(int a[])
{
int i;
for (i = 0; i < 5; i = i + 1)
{
cout<<a[i];
}
}
main()
{
cout << endl;
cobegin
{
int a[5] = {1,2,3,4,5};
Print(a);
}
}

How to decode a Bluetooth LE Package / Frame / Beacon of a FreeTec PX-1737-919 Bluetooth 4.0 Temperature Sensor?

The Sensor advertises these Bluetooth LE Packages:
> 04 3E 26 02 01 03 01 B8 AB C0 5D 4C D9 1A 02 01 04 09 09 38
42 42 41 43 34 39 44 07 16 09 18 47 08 00 FE 04 16 0F 18 5B
B3
> 04 3E 26 02 01 03 01 B8 AB C0 5D 4C D9 1A 02 01 04 09 09 38
42 42 41 43 34 39 44 07 16 09 18 45 08 00 FE 04 16 0F 18 5A
BC
> 04 3E 26 02 01 03 01 B8 AB C0 5D 4C D9 1A 02 01 04 09 09 38
42 42 41 43 34 39 44 07 16 09 18 44 08 00 FE 04 16 0F 18 5B
B2
How do I decode it?
LE Advertising Report:
ADV_NONCONN_IND - Non connectable undirected advertising (3)
bdaddr D9:4C:5D:C0:AB:B8 (Random)
Flags: 0x04
Complete local name: '8BBAC49D'
Unknown type 0x16 with 6 bytes data
Unknown type 0x16 with 3 bytes data
RSSI: -77
It's not a beacon advertisement. The packets are the device sending three pieces of information.
The device's local name "8BBAC49D"
The Health Thermometer Service is available (with a current temperature measurement)
The Battery Service is available (with a current battery level measurement)
Breakdown of this BLE discovered packet:
> 04 3E 26 02 01 03 01 B8 AB C0 5D 4C D9 1A 02 01 04 09 09 38
42 42 41 43 34 39 44 07 16 09 18 44 08 00 FE 04 16 0F 18 5B
B2
If you look at your repeat packet, you will see that each temperature measurement varies slightly, as does the battery measurement.
Here is the breakdown of the packet:
B8 AB C0 5D 4C D9 1A # Bluetooth Mac Address
02 # Number of bytes that follow in first AD structure
01 # Flags AD type
04 # Flags value 0x04 = 000000100
bit 0 (OFF) LE Limited Discoverable Mode
bit 1 (OFF) LE General Discoverable Mode
bit 2 (ON) BR/EDR Not Supported
bit 3 (OFF) Simultaneous LE and BR/EDR to Same Device Capable (controller)
bit 4 (OFF) Simultaneous LE and BR/EDR to Same Device Capable (Host)
09 # Number of bytes that follow in the first AD Structure
09 # Complete Local Name AD Type
38 42 42 41 43 34 39 44 # "8BBAC49D"
07 # Number of bytes that follow in the second AD Structure
16 # Service Data AD Type
09 18 # 16-bit Service UUID 0x1809 = Health thermometer (org.bluetooth.service.health_thermometer)
44 08 00 FE # Additional Service Data 440800 (Temperature = 0x000844 x 10^-2) = 21.16 degrees
04 # Number of bytes that follow in the third AD Structure
16 # Service Data AD Type
0F 18 # 16-bit Service UUID 0x180F = Battery Service (org.bluetooth.service.battery_service)
5B # Additional Service Data (battery level)
B2 # checksum
See the bluetooth 16-bit service UUID definitions for more information:
https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.battery_service.xml
https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.health_thermometer.xml
You can use hcidump -w dump.log to record some packages and open it in Wireshark - which does most of the decoding for you.
The missing pices:
04 # HCI Packet Type: HCI Event (0x04)
3E # Event Code: LE Meta (0x3e)
26 # Parameter Total Length: 38
02 # Sub Event: LE Advertising Report (0x02)
01 # Num Reports: 1
03 # Event Type: Non-Connectable Undirected Advertising (0x03)
01 # Peer Address Type: Random Device Address (0x01)
Screenshot form Wireshark:
And here is the Packet in btsnoop.log format. Works with Wireshark and hcidump -r packet.log.
public class Util {
public static int convertU16ToInt(byte i) {
int firstByte = (0x000000FF & ((int)i));
return firstByte;
}
public static int bytesToInt(final byte[] array, final int start)
{
final ByteBuffer buf = ByteBuffer.wrap(array); // big endian by default
buf.position(start);
buf.put(array);
buf.position(start);
return buf.getInt();
}
public static int convertU32ToInt(byte b[], int start) {
return ((b[start] << 24) & 0xff000000 |(b[start + 1] << 16) & 0xff0000
| (b[start + 2] << 8) & 0xff00 | (b[start + 3]) & 0xff);
}
public static long int64Converter(byte buf[], int start) {
return ((buf[start] & 0xFFL) << 56) | ((buf[start + 1] & 0xFFL) << 48)
| ((buf[start + 2] & 0xFFL) << 40)
| ((buf[start + 3] & 0xFFL) << 32)
| ((buf[start + 4] & 0xFFL) << 24)
| ((buf[start + 5] & 0xFFL) << 16)
| ((buf[start + 6] & 0xFFL) << 8)
| ((buf[start + 7] & 0xFFL) << 0);
}
public static long convertU16ToInt(byte[] buf, int index) {
int firstByte = (0x000000FF & ((int)buf[index]));
int secondByte = (0x000000FF & ((int)buf[index+1]));
int thirdByte = (0x000000FF & ((int)buf[index+2]));
int fourthByte = (0x000000FF & ((int)buf[index+3]));
index = index+4;
long anUnsignedInt = ((long) (firstByte << 24
| secondByte << 16
| thirdByte << 8
| fourthByte))
& 0xFFFFFFFFL;
return anUnsignedInt;
}
public static short toUnsigned(byte b) {
return (short)(b & 0xff);
}
public static int convertU16ToInt(byte byte1, byte byte2) {
int N = (( 255 - byte1 & 0xff ) << 8 ) | byte2 & 0xff;
return N;
}
public static short UInt16Decode(byte inbyByteA, byte inbyByteB) {
short n = (short)(((inbyByteA & 0xFF) << 8) | (inbyByteB & 0xFF));
return n;
}
public static long UInt32Decode(int inbyByteA, int inbyByteB) {
int n = inbyByteA<< 16 | inbyByteB;
return n;
}
public static long decodeMeasurement16(byte byte3, byte byte4) {
return 0L;
}
public static double decodeMeasurement32(byte byte3, byte byte4, byte byte6, byte byte7) {
double outdblFloatValue = 0;
int outi16DecimalPointPosition = 0;
int ui16Integer1 = convertU16ToInt (byte3, byte4);
int ui16Integer2 = convertU16ToInt (byte6, byte7);
int ui32Integer = ( (int)UInt32Decode (ui16Integer1, ui16Integer2) ) & 0x07FFFFFF;
outi16DecimalPointPosition = ((0x000000FF - byte3 ) >> 3) - 15;
// Decode raw value, with Exampledata: 0x05FFFFFC
if ((100000000 + 0x2000000) > ui32Integer) {
// Data is a valid value
if (0x04000000 == (ui32Integer & 0x04000000)) {
ui32Integer = (ui32Integer | 0xF8000000);
// With Exampledata: 0xFDFFFFFC
}
ui32Integer = ui32Integer + 0x02000000; // with Exampledata: 0xFFFFFFFC
}
else {
// Data contains error code, decode error code
outdblFloatValue = (double)((ui32Integer - 0x02000000) - 16352.0);
outi16DecimalPointPosition = 0;
return -36; // Return value is error code
}
outdblFloatValue = (double)ui32Integer;
outdblFloatValue = outdblFloatValue / (Math.pow(10.0f, (double)outi16DecimalPointPosition));
return outdblFloatValue;
}
public static int toByte(int number) {
int tmp = number & 0xff;
return (tmp & 0x80) == 0 ? tmp : tmp - 256;
}
public static long getUnsignedInt(int x) {
return x & 0x00000000ffffffffL;
}
}
After getting bytes array, call Util.decodeMeasurement32(byte[9], byte[10], byte[11], byte[12]). These bytes are the temperature bytes.
The thermometer works like a BLE beacon, i.e. you cannot connect. All information is given in the advertising every 5 seconds or so. E.g. with Android & the blessed library (https://github.com/weliem/blessed-android):
lateinit var central: BluetoothCentralManager
val HTS_SERVICE_UUID = ParcelUuid.fromString("00001809-0000-1000-8000-00805f9b34fb")
val BTS_SERVICE_UUID = ParcelUuid.fromString("0000180f-0000-1000-8000-00805f9b34fb")
fun convertTemperature(bytes: ByteArray?): Float {
if (null == bytes)
return -273.15f
val bb: ByteBuffer = ByteBuffer.allocate(2)
bb.order(ByteOrder.LITTLE_ENDIAN)
bb.put(bytes[0])
bb.put(bytes[1])
return bb.getShort(0) / 100.0f
}
val bluetoothCentralManagerCallback: BluetoothCentralManagerCallback = object : BluetoothCentralManagerCallback() {
override fun onDiscoveredPeripheral(peripheral: BluetoothPeripheral, scanResult: ScanResult) {
val rssi = scanResult.rssi
val scanRec = scanResult.scanRecord
val payload = scanRec?.serviceData
val temperature = convertTemperature(payload?.get(key = HTS_SERVICE_UUID))
val other_data = payload?.get(key = HTS_SERVICE_UUID)?.sliceArray(2..3)
val battery_level = payload?.get(key = BTS_SERVICE_UUID)
central.stopScan()
tempLabel.text = getString(R.string.temp, temperature)
}
}
central = BluetoothCentralManager(applicationContext, bluetoothCentralManagerCallback, Handler(Looper.getMainLooper()))
central.scanForPeripheralsWithNames(arrayOf("7FE2183D"))
Every time you want a new reading you can start scanning again.

How to check equivalent of randomly generated alphabets?

//This code gives randomly generated alphabets and if equal will
//cout the alphabet which is equal
1 #include <iostream>
2 #include <cstdlib>
3 #include <ctime>
4 using namespace std;
5 int main()
6 {
7 int a;
8 char array[10];
9 srand (time(0));
10 for (int i=0; i<10; i++)
11 {
12 a=rand() %26;
13 a=a+97;
14 array[i]=char(a);
15 }
16 for (int i=0; i<10; i++)
17 {
18 for (int j=0; j<10; j++)
19 {
20 if (array [i]==array [j]);
21 {
22 cout <<array[i] <<" " <<array[j];//if alphabet 'c' is at indecis 2,5,8
//then output should be like that of
// only 22 no statement but actually it does
// not give this answer but gives wrong output
//c c
//c c
//c c
23 }
24 cout << endl;
25 }
26 }
27 return 0;
28 } //program end
My question is how to check that randomly generated alphabets are equal e.g in 22 number line it should give output of equal alphabets if they are equal but it does not give equal alphabets what wrong in this code mention the wrong statement or help me how will i get right answer
Actually i want to make a program that should tell me how many times a single generated alphabet comes in an array
According to your comment you're looking for something that does this:
#include <random>
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
int main(){
::std::vector<char> letters(10);
::std::vector<char> unique;
::std::random_device rd;
::std::mt19937 mt(rd());
::std::uniform_int_distribution<char> dis('a', 'z');
auto random = ::std::bind(dis, mt);
// fill the vector with random letters
for(char & l : letters){
l = random();
}
int max_count = 0;
char appeared_most = ' ';
// get a vector of all the unique values
::std::unique_copy(letters.cbegin(), letters.cend(), ::std::back_inserter(unique));
// find the first value to appear most if two values appear equally
// the first will be chosen
for(const char & l : unique){
int count = ::std::count(letters.cbegin(), letters.cend(), l);
if(count > max_count){
max_count = count;
appeared_most = l;
}
}
::std::cout << appeared_most << " " << max_count ;
}
I have a working sample here: http://coliru.stacked-crooked.com/a/53c953576e0db756

C++ converting hex number to human readable string representation

I have a char[32] that consist of ASCII characters, some of which may be non printable characters, however, they are all in valid range of 0 to 255.
Let's say, it contains these numbers:
{ 9A 2E 5C 66 26 3D 5A 88 76 26 F1 09 B5 32 DE 10 91 3E 68 2F EA 7B C9 52 66 23 9D 77 16 BB C9 42 }
I'd like to print out or store in std::string as "9A2E5C66263D5A887626F109B532DE10913E682FEA7BC95266239D7716BBC942", however, if I print it out using printf or sprintf, it will yield the ASCII representative of each number, and instead it will print out "ö.\f&=Zàv&Ò µ2fië>h/Í{…Rf#ùwª…B", which is the correct ASCII character representation, since: ö = 9a, . = 2e, ...
How do I reliably get the string representation of the hex numbers? ie: I'd expect a char[64] which contains "9A2E5C66263D5A887626F109B532DE10913E682FEA7BC95266239D7716BBC942" instead.
Thanks!
void bytesToHex(char* dest, char* src, int size) {
for (unsigned int i = 0; i < size; i++) {
sprintf(&dest[i * 2], "%02x", src[i]);
}
}
You'd have to allocate your own memory here.
It would be used like this:
char myBuffer[32]
char result[65];
bytesToHex(result, myBuffer, 32);
result[64] = 0;
// print it
printf(result);
// or store it in an std::string
std::string str = string(result);
I tried:
char szStringRep[64];
for ( int i = 0; i < 32; i++ ) {
sprintf( &szStringRep[i*2], "%x", szHash[i] );
}
it works as intended, but if it encountered a < 0x10 number, it will null terminated as it is printing 0
You can encode your string to another system like Base64, which is widely used when using encryption algorithms.

Resources