Passing a variable through signal and slot system in Qt [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So I want to pass a std::string variable through the signal and slot system in Qt; I have a class on heap called RecordTalks which emits a signal when received message from chat is longer than 25 signs.
The code is as follows:
#include "recordtalks.h"
// records chat to files RecordTalks::RecordTalks(QObject *parent) {
}
RecordTalks::~RecordTalks() {
std::cout << "destructor" << "\n"; }
void RecordTalks::run(QString data) {
std::cout << ">>> whole data is: " << data.toStdString() << " ------------------\n";
std::string text = data.toStdString();
extractNick(text);
extractRoom(text);
//std::cout << "save in recordTalks is: " << save << "\n";
if((nick.size()!=0 && room.size()!=0))
{
extractText(data);
pushToVector(removeDigitsAndSpecials(nick), subText);
}
else
return; }
void RecordTalks::run() {
save=false;
save = console.saveNowState();
if(save==true)
{
saveToFile(allTexts, "BOT"); //trigger line saving to file
file.close();
removeDuplicatedNicks();
createNickFiles(nicks_v);
match_nicks_and_allTexts(allTexts);
closeNickFiles();
nicks_v.clear();
nickAndFile_pair_vec.clear();
text.clear();
allTexts.clear();
nick.clear();
room.clear();
subText.clear();
save=false;
}
}
void RecordTalks::extractText(QString &data) {
std::string text = data.toStdString(); // tu zmiana
size_t pos, pos2;
if((pos=text.find("PRIVMSG #"))!=std::string::npos)
{
if((pos2=text.find(":",pos))!=std::string::npos)
{
subText = text.substr(pos2+1, text.size()-(pos2+1) );
if((pos=subText.find("\u0001ACTION "))!=std::string::npos)
{
subText = subText.substr(pos+8 , subText.size()-3-(pos+8));
}
else
std::cout << "subText: " << subText << "\n";
}
}
else //if nothing to write to log:
{
return ;
}
}
void RecordTalks::extractNick(std::string &text) {
Extract_NickAndRoom e;
QString temp = QString::fromStdString(text);
nick = e.extractNick(temp);
//std::cout << "nick is: " << nick << "\n";
}
void RecordTalks::extractRoom(std::string &text) {
Extract_NickAndRoom e;
QString temp = QString::fromStdString(text);
room = e.extractRoom(temp);
//std::cout << "room is: " << room << "\n"; }
void RecordTalks::pushToVector(std::string nick, std::string &subText)
//general vector with texts {
if(subText.size()>25 ) //if line of text from irc is bigger than 25 signs
{
std::pair<std::string, std::string> para = std::make_pair(nick, subText);
allTexts.push_back(para); // pair --> vector
emit textUpdateSignal(subText);
std::cout << "EMITTTTTTTTTTTTTTTTTTT " << "\n";
//std::cout << ">>> subText: " << subText << " nick: " << nick << " <<<" << "\n";
}
if(allTexts.size()==60)
{
saveToFile(allTexts, "BOT"); //trigger line saving to file
file.close();
removeDuplicatedNicks();
createNickFiles(nicks_v);
match_nicks_and_allTexts(allTexts);
closeNickFiles();
nicks_v.clear();
nickAndFile_pair_vec.clear();
text.clear();
allTexts.clear();
nick.clear();
room.clear();
subText.clear();
save=false;
}
}
void RecordTalks::saveToFile( std::vector< std::pair<std::string,
std::string> > &allTexts, std::string nickFileName) {
std::string address = "D:\\Qt_workspace\\weatherBot\\logs\\" + nickFileName + ".txt";
file.open(address, std::ios::out | std::ios::app);
for (int i = 0; i < allTexts.size(); ++i)
{
file << allTexts[i].second; //writes text to file, not the nicks
}
}
void RecordTalks::createNickFiles(std::vector<std::string> &nicks_v) {
/* make vector of pair nick and file, so we can identify the file name and then
put text-matching-to-file-nick with file name */
for (int i = 0; i < nicks_v.size(); ++i)
{
std::fstream file2("D:\\Qt_workspace\\weatherBot\\logs\\"+ nicks_v[i] + ".txt",
std::ios::out | std::ios::app);
std::pair<std::string, std::fstream> nickAndFile_pair;
nickAndFile_pair = std::make_pair(removeDigitsAndSpecials(nicks_v[i]),
std::move(file2));
nickAndFile_pair_vec.push_back(std::move(nickAndFile_pair));
}
}// nicks_v[i] put inside function removeDigitsAndSpecials(std::string& nick)
void RecordTalks::match_nicks_and_allTexts(std::vector<
std::pair<std::string, std::string> > allTexts) {
for (int i = 0; i < nickAndFile_pair_vec.size(); ++i)
{
for (int j = 0; j < allTexts.size(); ++j)
{
if(nickAndFile_pair_vec[i].first == allTexts[j].first)
{
nickAndFile_pair_vec[i].second << allTexts[j].second;
//nickAndFile_pair_vec[j].second.flush();
}
}
}
std::cout << "allTexts size in match_nicks_and_allTexts is: ";
std::cout << allTexts.size() << "\n";
}
void RecordTalks::removeDuplicatedNicks() {
std::vector< std::pair<std::string, std::string> > temp = allTexts;
std::cout << "temp size: " << temp.size() << "\n";
for (int i = 0; i < temp.size(); ++i)
{
for (int j = i+1; j < temp.size(); ++j)
{
if(temp[i].first == temp[j].first && i+1< temp.size())
{
temp.erase(temp.begin()+j);
j--;
}
}
}
for (int i = 0; i < temp.size(); ++i)
{
nicks_v.push_back(temp[i].first);
}
std::cout << "nicks_v.size: " << nicks_v.size() << "\n";
}
void RecordTalks::closeNickFiles() //closes separate nick files {
for (int i = 0; i < nickAndFile_pair_vec.size(); ++i)
{
nickAndFile_pair_vec[i].second.close();
}
std::cout << "Files closed..." << "\n"; }
std::string RecordTalks::removeDigitsAndSpecials(std::string& nick) {
for (int i = 0; i < nick.size(); ++i)
{
if(std::isalpha(nick[i]))
{
}
else if(std::isdigit(nick[i]))
{
nick.erase(nick.begin()+i);
std::cout << "removing: " << nick[i] << "\n";
i--;
}
else
{
nick.erase(nick.begin()+i);
std::cout << "removing: " << nick[i] << "\n";
i--;
}
}
return nick;
}
Then in another class i have the connect function. When i write it in this form:
connect(recordTalks, &RecordTalks::textUpdateSignal, this, &Socket::updateDatabaseSLOT);
the slot receives the signal. But when i write the function this way:
connect(recordTalks, SIGNAL(textUpdateSign(std::string)), this,
SLOT(updateDatabaseSLOT(std::string)));
the Slot is not fired. So my question is, what is the reason of that. In other cases the latter version works just fine.
The slot looks like this:
void Socket::updateDatabaseSLOT(std::string textUpdate)
{
std::cout << "updates text: << textUpdate << "\n";
database.push_back(textUpdate);
}

I think you have a typo in your connect statement. Qt can be frustrating that way. SIGNAL(textUpdateSign(std::string ) should probably be SIGNAL(textUpdateSignal(std::string ).

Related

protobuf C++ issue with functions and double cout [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Here is the code:
#include <iostream>
#include <fstream>
#include "Students.pb.h"
class IRepository {
virtual void Open() = 0; // binary decerialization
virtual void Save() = 0; // binary serialization
};
class IMethods {
virtual double GetAverageScore(const FullName& name) = 0;
virtual std::string GetAllInfo(const FullName& name) = 0;
virtual std::string GetAllInfo() = 0;
};
StudentsGroup group1;
class StudentGroup : public IRepository, public IMethods
{
public:
void Open() override
{
std::fstream in("D:\GeekBrains CPP\diff moments 7\studentsgroup.bin", std::ios_base::binary);
group1.ParseFromIstream(&in);
if (!group1.ParseFromIstream(&in))
{
std::cout << "Open error!" << std::endl;
}
}
void Save() override
{
std::fstream out("D:\GeekBrains CPP\diff moments 7\studentsgroup.bin", std::ios_base::binary);
group1.SerializeToOstream(&out);
}
double GetAverageScore(const FullName& name) override
{
int i = 0;
double average;
for (const auto& student : group1.sinfo())
{
if (student.sname().surname() == name.surname() && student.sname().name() == name.name())
{
std::cout << "Average score is: " << student.averagemark();
average = student.averagemark();
i++;
}
}
if (i == 0)
{
std::cout << "No such student has been found!" << std::endl;
}
else if (i >= 2)
{
std::cout << "There're more then 1 student with this surname!" << std::endl;
}
return average;
}
std::string GetAllInfo(const FullName& name) override
{
int i = 0;
for(const auto& student : group1.sinfo())
{
if (student.sname().surname() == name.surname() && student.sname().name() == name.name())
{
std::cout << "Full Name: " << student.sname().surname() << " " << student.sname().name() << " " << student.sname().patronymic() << \
" marks: " ;
for (auto mark : student.grade())
{
std::cout << mark << "";
}
std::cout << "average mark: " << student.averagemark();
i++;
}
}
if (i == 0)
{
std::cout << "No such student has been found!" << std::endl;
}
return {};
}
std::string GetAllInfo() override
{
for (const auto student : group1.sinfo())
{
std::cout << "Full Name: " << student.sname().surname() << " " << student.sname().name() << " " << student.sname().patronymic() << \
" marks: ";
for (auto mark : student.grade())
{
std::cout << mark << " ";
}
std::cout << "average mark: " << student.averagemark() << std::endl;
}
if (group1.sinfo_size() == 0)
{
std::cout << "There're no students in the group yet" << std::endl;
}
return {};
}
};
double average(const google::protobuf::RepeatedField<int32_t>& grades)
{
double s = 0;
for (const int& i : grades)
{
s += i;
}
return round((s / grades.size())*100)/100;
}
int main()
{
auto name1 = std::make_unique<FullName>();
name1->set_surname("Sergeev");
name1->set_name("Sergey");
name1->set_patronymic("Sergeevich");
auto student1 = std::make_unique<Student>();
student1->set_allocated_sname(name1.release());
student1->add_grade(5);
student1->add_grade(4);
student1->add_grade(4);
student1->set_averagemark(average(student1->grade()));
std::cout << student1->averagemark() << std::endl;
group1.mutable_sinfo()->AddAllocated(student1.release());
for (auto i : group1.sinfo())
{
std::cout << "Full Name: " << i.sname().surname() << " " << i.sname().name() << " " << i.sname().patronymic() << \
" marks: ";
for (auto mark : i.grade())
{
std::cout << mark << " ";
}
std::cout << "average mark: " << i.averagemark() << std::endl;
}
StudentGroup sg1;
sg1.GetAllInfo();
**sg1.GetAverageScore(student1->sname());**
}
and here is proto file:
syntax="proto3";
message FullName{
string Surname = 1;
string Name = 2;
optional string Patronymic = 3;
}
message Student{
FullName sName = 1;
repeated int32 Grade = 2;
double AverageMark = 3;
}
message StudentsGroup{
repeated Student sInfo = 1;
}
I have several issues I can't resolve:
When I cout averagemark with function GetAllInfo() or i.averagemark(), I get some rubbish but in case where I cout it as student1->averagemark() it worked well. How do I solve it?
I don't know how to enter arguments in functions double GetAverageScore(const FullName& name) override and std::string GetAllInfo(const FullName& name) override. Nothing I do seems to work. I get an exception:
inline const ::FullName& Student::_internal_sname() const {
const ::FullName* p = _impl_.sname_;
return p != nullptr ? *p : reinterpret_cast<const ::FullName&>(
::_FullName_default_instance_);
I'm new to programming so appreciate any help. Thanks!
student1 is a smart pointer and holds nullptr after student1.release() in
group1.mutable_sinfo()->AddAllocated(student1.release());
The student1 is owned by group1 since that moment. Call them
sg1.GetAverageScore(group1.sinfo(0).sname());
sg1.GetAllInfo(group1.sinfo(0).sname());

how to print on the same line inside function, avoid flush

I want to display a progress bar however putting the printing code inside a separate function seems to invoke an std::flush as each time the progress bar is printing in a new line. This did not happen when the code was used inline
The code:
#include <iostream>
#include <unistd.h>
void load(int curr, int total) {
std::cout << "\n[";
int pos = 50 * curr/total;
for (int i = 0; i < 50; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "]" << int(float(curr)/(float)total * 100.0) << " %\r";
std::cout.flush();
}
int main(){
for( int i = 0; i <= 5; i++ ){
load(i,5);
}
std::cout << std::endl;
return 0;
}
What it does:
[> ]0 %
[==========> ]20 %
[====================> ]40 %
[==============================> ]60 %
[========================================> ]80 %
[==================================================]100 %
What it's supposed to do: print all on the same line
The first line in your function outputs \n, which is what makes it print on a new line every iteration.
Fix:
#include <iostream>
void load(int curr, int total) {
std::cout << '[';
int pos = 50 * curr/total;
for (int i = 0; i < 50; ++i) {
if (i < pos) std::cout << '=';
else if (i == pos) std::cout << '>';
else std::cout << ' ';
}
std::cout << ']' << int(float(curr)/(float)total * 100.0) << " %\r" << std::flush;
}
int main(){
for( int i = 0; i <= 5; i++ ){
load(i, 5);
}
std::cout << '\n';
}

Memory being messed up while searching for relation in family tree

I am implementing class of wizards in this code but I have a serious problem with finding relation in wizards family tree. I am using a back tracking method to find all relation between two nodes but memory will start to being messed up in the middle of the task and I have no idea what should I do.
Here you can see implementation of this class using C++.
#include "Wizard.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Wizard::Wizard(string first_name, string surname, string occupation, string organization, string wand)
: first_name(first_name),surname(surname), occupation(occupation), organization(organization), wand(wand)
{
this->married=0;
this->wand="Dragon Hearstring";
this->occupation="Auror";
this->organization="Dumbledore Army";
};
void Wizard::set_first_name(string _name){
this->first_name = _name;
}
void Wizard::set_surname(string _surname){
this->surname = _surname;
}
void Wizard::set_occupation(string _occupation){
this->occupation = _occupation;
}
void Wizard::set_organization(string _organization){
this->organization = _organization;
}
void Wizard::set_wand(string _wand){
this->wand = _wand;
}
string Wizard::get_name(){
string name;
name = first_name + " " + surname;
return name;
}
string Wizard::get_occupation(){
return occupation;
}
string Wizard::get_organization(){
return organization;
}
string Wizard::get_wand(){
return wand;
}
void Wizard::print_parents(){
cerr << "Parents: ";
for (int i=0; i<parents.size(); i++){
cout << parents[i]->get_name();
if ( i!= parents.size() -1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::print_siblings(){
cerr <<"Siblings: ";
for (int i=0; i<siblings.size(); i++){
cout << siblings[i]->get_name();
if ( i < siblings.size() -1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::print_spouse(){
cerr <<"Spouse: ";
if (married==1)
cout << spouse->get_name();
cout << endl;
}
void Wizard::print_children(){
cerr <<"Children: ";
for (int i=0; i<children.size(); i++){
cout << children[i]->get_name();
if ( i < children.size() - 1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::operator*(Wizard& _spouse){
this->married=1;
_spouse.married=1;
cout << this->get_name() << " and " << _spouse.get_name() << endl;
this->spouse = &_spouse;
_spouse.spouse = this;
_spouse.print_spouse();
vector< Wizard* > these_two;
these_two.push_back(this);
these_two.push_back(&_spouse);
for (int i=0; i<this->children.size(); i++)
children[i]->parents = these_two;
for (int i=0; i<_spouse.children.size(); i++)
children[i]->parents = these_two;
}
void Wizard::operator+(Wizard& _child){
if (!search_in_vector(this->children,&_child))
this->children.push_back(&_child);
if (!search_in_vector(this->spouse->children,&_child))
this->spouse->children.push_back(&_child);
vector< Wizard* > these_two;
these_two.push_back(this);
these_two.push_back(this->spouse);
_child.parents=these_two;
_child.surname = this->surname;
for (int i=0; i<this->children.size(); i++){
if(!search_in_vector(_child.siblings,children[i]) && (children[i]!=&_child)){
_child.siblings.push_back(children[i]);
children[i]->siblings.push_back(&_child);
}
}
}
void Wizard::print_relation_with(Wizard& john_doe){
vector<string> path2;
vector< vector< string > > path1;
vector<Wizard*> nodes_in_the_way;
nodes_in_the_way.push_back(this);
if (this->get_name() == john_doe.get_name()){
cout << this->get_name() << " is " << john_doe.get_name() << endl;
return;
}
this- >search_for_relation(*this,john_doe,path1,path2,nodes_in_the_way);
if (path1.size() == 0){
cout << "no relation" << endl;
return;
}
path2=path1[0];
for (int i=1;i<path1.size();i++){
if (path1[i].size() < path2.size())
path2=path1[i];
}
cout << this->get_name() << " is ";
for (int i=0; i<path2.size(); i++)
cout << path2[i] << " of ";
cout << john_doe.get_name() << endl;
}
void Wizard::search_for_relation(Wizard& a,Wizard& b,vector< vector<string> > &path1,vector<string> &path2,vector< Wizard* > &nodes_in_the_way){
cerr << "////////////" << endl;
cerr << "IM INSIDE " << a.get_name() << " , SEARCHING FOR " << b.get_name() << " - " << path2.size() << endl;
cout << "PATH: ";
for (int i=0;i<nodes_in_the_way.size();i++)
cout << nodes_in_the_way[i]->get_name() << " ";
cout << endl;
a.print_spouse();
a.print_children();
a.print_parents();
if (a.get_name() == b.get_name() && path2.size()==0){
return;
}
if (a.get_name() == b.get_name() ){
path1.push_back(path2);
return;
}
if (a.married){
if (!search_in_vector(nodes_in_the_way,a.spouse)){
path2.push_back("spouse");
nodes_in_the_way.push_back(a.spouse);
search_for_relation(* (a.spouse),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
// parents
for (int i=0;i<a.parents.size();i++){
if (!search_in_vector(nodes_in_the_way,a.parents[i])){
path2.push_back("child");
nodes_in_the_way.push_back(a.parents[i]);
search_for_relation(* (a.parents[i]),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
// children
for (int i=0;i<a.children.size();i++){
if (!search_in_vector(nodes_in_the_way,a.children[i])){
path2.push_back("parent");
nodes_in_the_way.push_back(a.children[i]);
search_for_relation(* (a.children[i]),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
}
///////////// NON-METHOD FUNCITONS ///////////////
bool search_in_vector(vector< Wizard* > a,Wizard* b){
for (int i=0; i<a.size(); i++)
if (a[i]->get_name() == b->get_name())
return true;
return false;
}
So that was the code.
Here you can see the output after some back_tracking:
Here you see that Harry's information has been messed up during last recursion and the executable file can't print his parents.
Please let me know that I'm doing wrong! Thanks!

boost udp::socket closes, but not freeing socket UPDATE

UPDATE: If i change async_receive_from to receive_from then there will not be any problems with rebinding. Somehow async... causes that. Previously i had one thread for every socket(with receive_from), but i had to make it work in one thread as too many threads are spawned during programm runs.
Socket is closed (i have checked), but rebinding to it causes an error. Here is an example:
#include "stdafx.h"
#include "Mmsystem.h"// for accurate timers
#pragma comment (lib,"Winmm.lib")// for accurate timers
using namespace std;
typedef shared_ptr<boost::asio::ip::udp::socket> SHP_Socket;
boost::asio::io_service io_service_;
vector<int> ports;
vector<SHP_Socket> vecSock;
vector<boost::asio::ip::udp::endpoint> vecEndpoint;
vector<boost::shared_ptr<boost::thread>> receive_threads;
bool process_all_finishing;
uint8_t Data[8000];
void receive_h(boost::system::error_code ec, size_t szPack, int i)
{
if (process_all_finishing == false)
{
cout << "\n" << i;
string f = boost::to_string(Data);
int sz = f.size();
if (sz > 12)
{
vector<int> a;
for (int i = 0; i < 100; ++i)
a.push_back(i);
a.clear();
}
}
}
void Run_io()
{
while (process_all_finishing == false)
{
io_service_.run_one();
}
cout << "\nRun_io finished";
}
void receive()
{
while (process_all_finishing == false)
{
this_thread::sleep_for(chrono::milliseconds(1));
for (unsigned i = 0; i < vecSock.size(); ++i)
{
vecSock[i]->async_receive_from(boost::asio::buffer(Data, 8000), vecEndpoint[i], boost::bind(receive_h,_1,_2,i));
}
}
cout << "\nreceive finished";
}
int main()
{
timeBeginPeriod(1);
setlocale(LC_ALL, "Russian");
try
{
ports.push_back(29005);
ports.push_back(29007);
ports.push_back(29009);
ports.push_back(29001);
vecSock.resize(3);
vecEndpoint.resize(3);
for (int i = 0; i < 3; ++i)
{
vecSock[i].reset(new boost::asio::ip::udp::socket(io_service_, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), ports[i])));
}
boost::shared_ptr<boost::thread> thread_re(new boost::thread(receive));
boost::shared_ptr<boost::thread> thread_io(new boost::thread(Run_io));
receive_threads.push_back(thread_re);
receive_threads.push_back(thread_io);
cout << "\nvecSock=3 created, giving it to work for 1 second:";
this_thread::sleep_for(chrono::seconds(1));
process_all_finishing = true;
cout << "\nSent flag to stop threads and wait for threads to finish for 1 second";
this_thread::sleep_for(chrono::seconds(1));
for (int i = 0; i < vecSock.size(); ++i)
{
cout << "\nSocket " << i << " opened =\t" << vecSock[i]->is_open();
vecSock[i]->cancel();
vecSock[i]->close();
cout << "\nSocket " << i << " counter =\t" << vecSock[i].use_count();
cout << "\nSocket " << i << " opened =\t" << vecSock[i]->is_open();
vecSock[i].reset();
cout << "\nSocket " << i << " counter =\t" << vecSock[i].use_count();
cout << "\n";
}
this_thread::sleep_for(chrono::seconds(1));
vecSock.clear();
vecSock.resize(4);
vecEndpoint.resize(4);
for (int i = 0; i < 4; ++i)
{
vecSock[i].reset(new boost::asio::ip::udp::socket(io_service_, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), ports[i])));
}
cout << "\nvecSock=4 created";
}
catch (boost::exception& e)
{
cerr <<"\n\a\a"<< boost::diagnostic_information(e);
system("pause");
}
return 0;
}
This causes an binding error (exeption) which i have redirected to console with try-catch.
Throw location unknown (consider using BOOST_THROW_EXCEPTION) Dynamic
exception type: class boost::exception_detail::clone_impl > std::exception::what: bind: Usually are
allowed only one usage of each socket address (Protocol/network
address/port)
Can ony one help? I have tried all, what I could find in references c++ and boost and nothing helped this error.

display string sub vector C++

I am new in C++, I created a struct called Device with two fields
string MacAdress
vector<string> RSSI
Then, I created a vector of structure: vector<Device> Devices
I want to extract the vector<string> RSSI and display its contant.
Here is where I got stuck in my main.cpp:
cout << "display MAC and RSSI"<< endl;
Device CurrentDevice;
for(int j=0; j<Devices.size();j++)
{
CurrentDevice = Devices.at(j);
vector<string>::const_iterator begin = CurrentDevice.GetRSSIs().begin();
vector<string>::const_iterator last = CurrentDevice.GetRSSIs().begin() + CurrentDevice.GetRSSIs().size();
vector<string> intermed(begin+1, last);
cout << "Size: "<< intermed.size() << endl;
for (int i = 0 ; i < intermed.size(); i++)
{
cout << intermed[i] << endl;
cout << "device n°"<< j+1<<" " << "MAC "<< " "<< CurrentDevice.GetMacAdress()<< endl;
for(int k=0; k<intermed.size();k++)
{
cout << "device n°" << j;
cout << "\tRSSI " << k << " = " << intermed.at(k)<< endl;
}
}
return 0;
}
I end up with Size=0
here is some simplified code that does not use iterators but should still do the job:
#include <iostream>
#include <string>
#include <vector>
int main()
{
struct Device {
std::string MacAddress;
std::vector<std::string> RSSI;
};
std::vector<Device> Devices;
// add some stuff to first object
Device CurrentDevice1;
CurrentDevice1.MacAddress = "A-B-C";
CurrentDevice1.RSSI.push_back("rssi11");
CurrentDevice1.RSSI.push_back("rssi12");
CurrentDevice1.RSSI.push_back("rssi13");
Devices.push_back(CurrentDevice1);
// add some stuff to second object
Device CurrentDevice2;
CurrentDevice2.MacAddress = "D-E-F";
CurrentDevice2.RSSI.push_back("rssi21");
CurrentDevice2.RSSI.push_back("rssi22");
Devices.push_back(CurrentDevice2);
// see object MAC's
for (int i = 0; i < Devices.size(); i++){
std::cout << "device " << i+1 << " MAC: " << Devices[i].MacAddress << std::endl;
}
// see object RSSI's
for (int j = 0; j < Devices.size(); j++){
for (int k = 0; k < Devices[j].RSSI.size(); k++){
std::cout << "device " << j + 1 << " RSSI: " << k +1 << " : " << Devices[j].RSSI[k] << std::endl;
}
std::cout << "\n";
}
return 0;
}
I'm not sure about what do you want to obtain, but I suppose the problem is in the following lines
vector<string>::const_iterator last = CurrentDevice.GetRSSIs().begin() + CurrentDevice.GetRSSIs().size();
vector<string> intermed(begin+1, last);
Do you want to obtain a copy of CurrentDevice.GetRSSIs()?
In this case, you can use begin() and end()
vector<string> intermed(CurrentDevice().GetRSSIs().begin(),
CurrentDevice().GetRSSIs().end());
or, simpler, invoke the copy constructor,
vector<string> intermed(CurrentDevice().GetRSSIs());