Different behavior with similar code - c++11

#include <vector>
#include <iostream>
using namespace std;
struct A
{
vector<int> v;
};
void f0(const A&& a0)
{
cout << &a0.v[0] << endl;
A a1{ move(a0.v) };
cout << &a1.v[0] << endl << endl;;
}
void f1()
{
A a0{ vector<int>(10) };
cout << &a0.v[0] << endl;
A a1{ move(a0.v) };
cout << &a1.v[0] << endl;
}
int main()
{
f0(A{ vector<int>(10) });
f1();
return 0;
}
I can't understand why in the first case addresses are different but in the second case addresses are same.

Related

TCP echo server with boost asio

I am trying to make tcp echo server with boost asio.
I successed transport of string data to server from client.
But I can't transport received data from client to client.
I do not know if this problem is caused by async_write() function in server code or async_read() function in client code.
I suppose that this problem is caused by thread's declaration and their function call but, I'm not sure.
Summary : I don't know correct cause of this problem..
Help me please...
sever code
#include <iostream>
#include <boost/asio.hpp>
#include <cstring>
#include <cstdlib>
#include <memory>
#include <deque>
#include <list>
#include <set>
using boost::asio::ip::tcp;
typedef std::string echo_message;
class echo_session
: public std::enable_shared_from_this<echo_session>
{
public:
echo_session(tcp::socket socket, std::set<std::shared_ptr<echo_session>>& session_place)
: socket_(std::move(socket)),
session_place_(session_place)
{
std::cout << "Session Initializing...\n";
read_msg_ = "Server!";
}
void start()
{
int se_num=0;
std::cout << "Session starting...\n";
session_place_.insert(shared_from_this());
for(auto session: session_place_)
{
se_num++;
}
std::cout << "Session num: " << se_num << std::endl;
do_read_message();
}
void deliver(const echo_message& msg)
{
this->write_msg_ = msg;
do_write();
}
private:
void do_read_message()
{
auto self(shared_from_this());
char *read_buffer = new char[128];
std::cout << "Reading Message...\n";
boost::asio::async_read(socket_,
boost::asio::buffer(read_buffer, 128),
[this, self, read_buffer](boost::system::error_code ec, std::size_t)
{
if(!ec)
{
read_msg_ = read_buffer;
std::cout << "do_read_message() Message:" << read_msg_ << std::endl;
/*
/////////////////////////////
Used Debugging Part
////////////////////////////
std::cout << "Async Read! : ";
std::cout << read_msg_ << std::endl;
std::cout << "Length:" << read_msg_.length() << std::endl;
*/
deliver(read_msg_);
do_read_message();
}
else
{
std::cout << "Async Read Failed!\n";
std::cerr << "Error: " << ec.message() << std::endl;
}
});
std::cout << "do_read_message() is returned!\n";
}
void do_write()
{
auto self(shared_from_this());
char *read_buffer = new char[sizeof(write_msg_.c_str())];
memcpy(read_buffer, write_msg_.c_str(), sizeof(write_msg_.c_str()));
boost::asio::async_write(socket_,
boost::asio::buffer(read_buffer, sizeof(read_buffer)),
[this, self, read_buffer](boost::system::error_code ec, std::size_t)
{
if(!ec)
{
std::cout << "Message <" << read_buffer << ">Writed!\n";
this->write_msg_ = "\0";
}
else
{
std::cout << "Write Failed\n";
}
std::cout << "do_write lambda returned!\n";
});
}
tcp::socket socket_;
echo_message read_msg_;
echo_message write_msg_;
std::set<std::shared_ptr<echo_session>>& session_place_;
};
class echo_server {
public:
echo_server(boost::asio::io_context& io_context,
const tcp::endpoint& endpoint)
: acceptor_(io_context, endpoint)
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
[this](boost::system::error_code ec, tcp::socket socket)
{
if(!ec)
{
std::make_shared<echo_session>(std::move(socket), sessions_)->start();
std::cout << "Accept!\n";
}
else
{
std::cout << "Accept Failed!\n";
}
do_accept();
});
}
tcp::acceptor acceptor_;
std::set<std::shared_ptr<echo_session>> sessions_;
};
int main(int args, char *argv[])
{
try
{
if( args != 2)
{
std::cerr << "Usage: server <port>" << std::endl;
return 1;
}
boost::asio::io_context io_context;
tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[1]));
echo_server ex_server(io_context, endpoint);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
client code
#include <iostream>
#include <deque>
#include <thread>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
typedef std::string echo_message;
class echo_client {
public:
echo_client(boost::asio::io_context& io_context,
const tcp::resolver::results_type& endpoints)
: io_context_(io_context),
socket_(io_context)
{
do_connect(endpoints);
}
void write(const std::string string)
{
boost::asio::post(io_context_,
[this, string]()
{
//std::cout << "Post Success!\n";
do_write(string);
});
}
void close()
{
boost::asio::post(io_context_,
[this]()
{
std::cout << "Close Success!\n";
socket_.close();
});
}
private:
void do_connect(const tcp::resolver::results_type& endpoints)
{
boost::asio::async_connect(socket_, endpoints,
[this](boost::system::error_code ec, tcp::endpoint)
{
if(!ec)
{
std::cout << "Async_connect Success!\n";
do_read_message();
}
else
{
std::cout << "Async_connect error!\n";
}
});
}
void do_read_message()
{
std::cout << "read_message()" << std::endl;
//auto self(shared_from_this());
char *read_buffer = new char[128];
boost::asio::async_read(socket_,
boost::asio::buffer(read_buffer, 128),
[this, read_buffer/*, self*/](boost::system::error_code ec, std::size_t size)
{
if(!ec)
{
std::cout << "Async Read Success!\n";
read_msg_ = read_buffer;
if(read_msg_.length() != 0)
{
std::cout << "Message:" << read_msg_ << std::endl;
std::cout << "Length: " << read_msg_.length() << std::endl;
read_msg_ = "\0";
}
do_read_message();
}
else
{
std::cout << "Async_read error!\n";
std::cerr << "Error:" << ec.message() << std::endl;
socket_.close();
}
});
std::cout << "do_read_message() is returned!\n";
}
void do_write(const std::string string)
{
write_msg_ = string;
char *str = new char[sizeof(string.c_str())];
memcpy(str,string.c_str(),sizeof(string.c_str()));
boost::asio::async_write(socket_,
boost::asio::buffer(str, 128),
[this](boost::system::error_code ec, std::size_t)
{
if(!ec)
{
std::cout << "Transport Success!" << std::endl;
}
});
}
private:
boost::asio::io_context& io_context_;
tcp::socket socket_;
echo_message read_msg_;
echo_message write_msg_;
};
int main(int argc, char *argv[])
{
try
{
if(argc != 3)
{
std::cerr << "Usage: client <host> <port>" << std::endl;
return 1;
}
boost::asio::io_context io_context;
tcp::resolver resolver(io_context);
auto endpoints = resolver.resolve(argv[1], argv[2]);
echo_client c(io_context, endpoints);
std::thread t(
[&io_context]()
{
io_context.run();
});
std::string line;
while(std::cin >> line)
{
echo_message msg;
msg = line;
c.write(msg);
}
c.close();
t.join();
}
catch(std::exception e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}

.compare not matching a string pulled from an object

I am trying to go threw a vector of Student objects. If I find a matching ID to the one I am searching for it will display their info.
However, when I try to find a specific ID .compare isn't seeing a match even though it should.
My output: first line is the ID I am looking for, second is the current ID being looked at, then is the result of the compare.
a11111111
a22222222
-1
no match
a11111111
a11111111
-1
no match
Asked for more of the code so here is the entire program: (issue in displayID)
header file
#ifndef structures_h
#define structures_h
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <map>
using namespace std;
main program
#endif
typedef pair<string, string> Name; // first name, last name
typedef map<string, int> Grades; // map courses to scores
#include "struct.h"
class Student {
public:
void display(ostream& os) const;
void setId(string);
void setName(string, string);
void setGrades(string, int);
string getId();
string getName();
void getGrades();
bool operator<(const Student &rhs) const { return id_ < rhs.id_; }
private:
string id_; // e.g. "a22222222"
Name name_; // e.g. {"ned", "flanders"}
Grades grades_;
};
void Student::setId(string id) {
id_ = id;
}
string Student::getId() {
return id_;
}
void Student::setName(string first, string last) {
name_ = pair<string,string>(first, last);
}
string Student::getName() {
return get<0>(name_) + ' ' + get<1>(name_);
}
void Student::setGrades(string course, int score) {
grades_.insert(make_pair(course, score));
}
void Student::getGrades() {
for(auto it = grades_.begin(); it != grades_.end(); ++it) {
cout << it -> first << ' ' << it -> second << endl;
}
}
vector<Student> addStudent(int count, int x, vector<Student>& vStu, string file) {
string line, first, last;
ifstream infile(file);
while (getline(infile, line)) {
vStu.push_back(Student());
vStu[count].setId(line);
getline(infile, line);
istringstream iss(line);
if (!(iss >> first >> last)) {
cout << "failed to get name" << endl;
break;
}
vStu[count].setName(first, last);
getline(infile, line);
istringstream iss2(line);
if (!(iss2 >> x)) {
cout << "failed to get class number" << endl;
break;
}
for (int i = 0; i < x; i++) {
string sClass;
int grade;
getline(infile, line);
istringstream iss3(line);
if (!(iss3 >> sClass >> grade)) {
cout << "failed to get class and grade" << endl;
break;
}
vStu[count].setGrades(sClass, grade);
}
count++;
}
return vStu;
}
void display(vector<Student>& vStu) {
sort(vStu.begin(), vStu.end());
cout << endl;
int count = vStu.size();
for (int i = 0; i<count;i++) {
cout << vStu[i].getId() << endl;
cout << vStu[i].getName() << endl;
vStu[i].getGrades();
cout << endl;
}
}
void displayID(vector<Student>& vStu, string ID) {
int count = vStu.size();
string test;
ID = "a11111111";
for (int i = 0; i<count;i++) {
cout<< endl;
test = vStu[i].getId();
cout << ID << endl;
cout << test << endl;
cout << ID.compare(test) << endl;
if (ID.compare(test) == 0) {
cout << "match" << endl;
cout << vStu[i].getId() << endl;
cout << vStu[i].getName() << endl;
vStu[i].getGrades();
cout << endl;
} else {
cout << "no match" << endl;
}
}
cout << endl;
}
void mainMenu(vector<Student>& vStu) {
string input;
string word;
vector<string> com;
while(1) {
cout << "Enter command: ";
getline(cin,input);
istringstream iss(input);
while(iss >> word) {
com.push_back(word);
}
for (int i = 0; i < (int)com.size(); i++) {
transform(com[i].begin(), com[i].end(), com[i].begin(), ::tolower);
if (com[i] == "show") {
display(vStu);
} else if (com[i] == "showid") {
displayID(vStu, "a11111111");
}
}
com.clear();
}
}
int main(int argc, char *argv[]) {
vector<Student> vStu;
int count = 0, x = 0;
if (argc != 2) {
cout << "Incorrectly called" << endl;
cout << " " << argv[0] << ' ' << "<filename>" << endl;
return 1;
}
addStudent(count, x, vStu, argv[1]);
mainMenu(vStu);
}
The only possibility I see is that there is some whitespace at the end of the string that gets passed into your function. Try trimming the end of the string's like this this thread suggests before comparing and see if they still don't compare correctly.

How to get error object? when use member function in deadline_timer

I use boost::asio::deadline_timer using a member function as a handler (callback function).
If I cancel a timer, how to get error object in print() member function?
class printer
{
public:
printer(boost::asio::io_service& io)
: timer_(io, boost::posix_time::seconds(1)),
count_(0)
{
timer_.async_wait(boost::bind(&printer::print, this));
}
~printer()
{
std::cout << "Final count is " << count_ << "\n";
}
void print()
{
if (count_ < 5)
{
std::cout << count_ << "\n";
++count_;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(boost::bind(&printer::print, this));
}
}
private:
boost::asio::deadline_timer timer_;
int count_;
};
int main()
{
boost::asio::io_service io;
printer p(io);
io.run();
return 0;
}
I try to set error object using bind in async_wait(), but it's compile error
timer_.async_wait(boost::bind(&printer::print, this, boost::asio::placeholders::error));
As long as your method signature matches, it should be no problem:
void print(boost::system::error_code const ec)
// and
boost::bind(&printer::print, this, boost::asio::placeholders::error)
See it Live On Coliru:
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>
class printer
{
public:
printer(boost::asio::io_service& io)
: timer_(io, boost::posix_time::seconds(1)),
count_(0)
{
timer_.async_wait(boost::bind(&printer::print, this, boost::asio::placeholders::error));
}
~printer()
{
std::cout << "Final count is " << count_ << "\n";
}
void print(boost::system::error_code const ec)
{
if (ec)
std::cout << "Error: " << ec.message() << "\n";
if (count_ < 5)
{
std::cout << count_ << "\n";
++count_;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(boost::bind(&printer::print, this, boost::asio::placeholders::error));
}
}
private:
boost::asio::deadline_timer timer_;
int count_;
};
int main()
{
boost::asio::io_service io;
printer p(io);
io.run();
}

How to set and get graph property from boost graph library?

I don't know how to set and get graph_name as property from adjacency_list graph. I am able to put and get vertex and edge properties.
Any help would be appreciated.
First thing is to define classes to hold the properties for vertex, edge and graph
class cVertexProps {
...
}
class cEdgeProps {
...
}
class cGraphProps {
public:
std::string myName;
...
};
Now define your graph
typedef boost::adjacency_list <
boost::vecS, boost::vecS, boost::undirectedS,
cVertexProps, cEdgeProps, cGraphProps >
graph_t;
graph_t myGraph;
... and so set your graph name
myGraph[graph_bundle].myName= "My First Graph";
This uses "bundled properties", which are described here: http://www.boost.org/doc/libs/1_55_0/libs/graph/doc/bundles.html
I have solution for boost subgraph(just try it for graph it will work for sure) property get and set as below:-
#include <QtCore/QCoreApplication>
#include <boost/config.hpp>
#include <iostream>
#include <algorithm>
#include <boost/graph/adjacency_list.hpp>
#include <boost/property_map/property_map.hpp>
#include <string>
#include <boost/graph/subgraph.hpp>
#include <QMap>
using namespace std;
using namespace boost;
enum graph_IDproperty_t
{
graph_IDproperty
};
namespace boost
{
BOOST_INSTALL_PROPERTY(graph,IDproperty);
}
struct GraphProperties {
std::string strName;
std::string id;
};
typedef boost::subgraph<
boost::adjacency_list<
boost::listS, boost::vecS, boost::bidirectionalS,
boost::property<boost::vertex_index_t, int,
property< boost::vertex_color_t, boost::default_color_type > >,
boost::property<boost::edge_index_t, int,
property<boost::edge_color_t, default_color_type> >,
boost::property<graph_IDproperty_t,GraphProperties>
>
> Graph;
Graph gMainGraph;
typedef QMap<Graph*,GraphProperties*> mapGraphToProperty;
mapGraphToProperty getMap(Graph& graph);
void graphMapRecur(mapGraphToProperty& map, Graph& graph);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Graph& subG = gMainGraph.create_subgraph();
Graph& subG1 = gMainGraph.create_subgraph();
boost::ref_property_map<Graph*, GraphProperties>
graph_propt1(boost::get_property(subG1,graph_IDproperty));
graph_propt1[&subG1].id = "SubG1";
cout << graph_propt1[&subG1].id << endl;
boost::ref_property_map<Graph*, GraphProperties>
graph_propt(boost::get_property(subG,graph_IDproperty));
graph_propt[&subG].id = "SubG";
cout << graph_propt[&subG].id << endl;
boost::ref_property_map<Graph*, GraphProperties>
graph_proptMain(boost::get_property(gMainGraph,graph_IDproperty));
graph_proptMain[&gMainGraph].id = "gMain";
cout << graph_proptMain[&gMainGraph].id << endl;
mapGraphToProperty map = getMap(gMainGraph);
boost::ref_property_map<Graph*, GraphProperties>
graph_proptMain1(*(map.value(&gMainGraph)));
boost::ref_property_map<Graph*, GraphProperties>
graph_proptsubG(*(map.value(&subG)));
boost::ref_property_map<Graph*, GraphProperties>
graph_proptsubG1(*(map.value(&subG1)));
cout << "Main G Value : " << graph_proptMain1[&gMainGraph].id << endl;
cout << "Sub G Value : " << graph_proptsubG[&subG].id << endl;
cout << "Sub G1 Value : " << graph_proptsubG1[&subG1].id << endl;
cout << "Map Value Main: " << (map.value(&gMainGraph)) << endl;
cout << "Map Value SubG: " << (map.value(&subG)) << endl;
cout << "Map Value SubG1b: " << (map.value(&subG1)) << endl;
return a.exec();
}
mapGraphToProperty getMap(Graph &graph)
{
mapGraphToProperty map;
graphMapRecur(map,graph);
return map;
}
void graphMapRecur(mapGraphToProperty &map, Graph &graph)
{
Graph::children_iterator itrSubgraph, itrSubgraph_end;
for (boost::tie(itrSubgraph, itrSubgraph_end) = (graph).children();
itrSubgraph != itrSubgraph_end; ++itrSubgraph)
{
graphMapRecur(map,(*itrSubgraph));
}
GraphProperties* gp = &(get_property(graph,graph_IDproperty));
map.insert(&graph,gp);
cout << "Recurrr" << endl;
}

Error: Identifier "PrintGuessesRemaining" , "PrintWordSpaceDelinated" , "PrintWordsRemainingIsUndefined"

I have Created a Print Class where I have created all of those functions.
When I attempt to call these functions, I get the Identifier Error. I am sure I have incorrectly set up my class. Please Help construct Print Class
Code attached:
// Print.cpp - Print Class implementation
// Written by Varun Patel
#include "Print.h"
Print::Print()
{
}
Print::Print(const string& word)
{
Word = word;
}
void Print::PrintWordsRemaining(set<string>& possibleWords_, bool displayNumberOfWordsRemaining_)
{
if(displayNumberOfWordsRemaining_)
{
cout << "There are " << possibleWords_.size() << " possible words left." << endl;
}
else
{
//Do nothing
}
}
void Print::PrintWordSpaceDelinated(string word_)
{
for (size_t i = 0; i < word_.size(); i++)
{
cout << word_[i] << " ";
}
cout << endl;
}
void Print::PrintGuessesRemaining(int guessesRemaining_)
{
cout << "You have " << guessesRemaining_ << " guesses remaining." << endl;
}
Here is how i try to call one of the functions:
#include "UpdateGuessesRemaining.h"
void UpdateGuessesRemaining(set<string>& newPossibleWords, int& guessesRemaining,
char guessChar, string& guessedWord)
{
set<string>::iterator wordPtr = newPossibleWords.begin();
if (wordPtr->find(guessChar) == -1)
{
cout << "Sorry, incorrect guess. ";
PrintGuessesRemaining(--guessesRemaining);
}
else
{
cout << "Correct! The word contains " << guessChar << "." << endl;
}
}
Here is my header File:
// Print.h - Print Class declaration
// Written by Varun Patel
#pragma once
#include <iostream>
#include <set>
#include <string>
#include "PromptForGuessesRemaining.h"
using namespace std;
class Print
{
public:
// Default constructor
Print();
Print(const string& word);
void PrintWordsRemaining(set<string>& possibleWords, bool displayNumberOfWordsRemaining);
void PrintWordSpaceDelinated(string word);
void PrintGuessesRemaining(int guessesRemaining);
private:
string Word;
};
Thanks For Your Help,
Varun

Resources