Olivier Grech Olivier Grech - 1 year ago 108
C++ Question

Iterating over a vector

I'm trying to complete some code for an homework.

It involves (among other things) iterating over a vector and I'm getting a strange result.


#include "tp1.hpp"

int main(int argc, char** argv) {

std::vector<uint8_t> signal { 1,2,0,0,1,2,1,0,2,1,2,1,0,0,0,1,2,1 };
std::vector<LZ77Code> code = lz77_encode(signal, 18, 9);

return 0;


inline std::vector<LZ77Code> lz77_encode(const std::vector<uint8_t>& vSignal, size_t N, size_t n1) {

std::vector<LZ77Code> vCode;

std::vector<uint8_t>::const_iterator vSignalIt; //Iterator for the vector in the parameters

vSignalIt = vSignal.begin();
while (vSignalIt != vSignal.end())
std::cout << *vSignalIt << std::endl;

return vCode;

I'm getting this printed in the console as a result :

Not really what I intended, you guessed it. I shortened the code to the bare minimum because It's been a while since I dealt with C++ and I feel like I'm making a trivial error. Let me know if you need more details.

Thanks for your time!

Answer Source

When you write uint8_t to cout, it treats it as a char. You need to cast to int.

std::cout << static_cast<int>(*vSignalIt) << std::endl; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download