I have looked through stackoverflow and added an overload operator to hopefully make it work with sort. Though I still get an explosion of an error saying something is wrong with sort.
Code:
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <algorithm>
class Student
{
private:
std::string name_;
int number_;
std::vector<int> grades_;
const int num_courses_;
static std::string gen_name() {
return std::to_string(rand());
}
static int gen_number() {
return rand() % (201600000 - 201100000 + 1) + 201100000;
}
static int gen_grade() {
return rand() % (100 - 70 + 1) + 70;
}
double compute_average() {
int marks = 0;
int count = 0;
for (std::vector<int>::iterator i = grades_.begin(); i != grades_.end(); i++, count++){
marks += *i;
}
return static_cast<double>(marks) / count;
}
public:
Student() : name_(gen_name()), number_(gen_number()), num_courses_(5)
{
for (int i = 0; i < num_courses_; ++i) {
grades_.push_back(gen_grade());
}
}
double getAvg() {
return compute_average();
}
friend std::ostream& operator<<(std::ostream& os, Student& s) {
os << "Name = " << s.name_ << "\tNumber = " << s.number_ << "\tAvg = " << s.compute_average();
return os;
}
std::string getName() {
return name_;
}
void print_grades(std::ostream& os) const
{
for (int i = 0; i < num_courses_; ++i) {
os << grades_[i] << ", ";
}
}
bool operator < (const Student& str) const
{
return (name_ < str.name_);
}
};
int main(int argc, char ** argv) {
srand(time(NULL));
if (argc == 2){
int numbOfStudents = atoi(argv[1]);
std::vector<Student> studentVec;
for (int i = 0; i < numbOfStudents; i++){
studentVec.push_back(Student());
}
std::sort(studentVec.begin(), studentVec.end());
for (std::vector<Student>::iterator xi = studentVec.begin(); xi != studentVec.end(); xi++) {
std::cout << *xi << std::endl;
}
}
else{
std::cout << "Usage: " << argv[0] << " {numb} " << std::endl;
}
return 0
}
The error comes when I run sort (I know it's sort since if I comment it out, it works properly). With the error code
In file included from /usr/include/c++/4.9/algorithm:62:0,
from main.cpp:5:
/usr/include/c++/4.9/bits/stl_algo.h: In instantiation of ‘void std::__insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Student*, std::vector<Student> >; _Compare = __gnu_cxx::__ops::_Iter_less_iter]’:
/usr/include/c++/4.9/bits/stl_algo.h:1884:70: required from ‘void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Student*, std::vector<Student> >; _Compare = __gnu_cxx::__ops::_Iter_less_iter]’
/usr/include/c++/4.9/bits/stl_algo.h:1970:55: required from ‘void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Student*, std::vector<Student> >; _Compare = __gnu_cxx::__ops::_Iter_less_iter]’
/usr/include/c++/4.9/bits/stl_algo.h:4685:72: required from ‘void std::sort(_RAIter, _RAIter) [with _RAIter = __gnu_cxx::__normal_iterator<Student*, std::vector<Student> >]’
main.cpp:79:50: required from here
/usr/include/c++/4.9/bits/stl_algo.h:1851:17: error: use of deleted function ‘Student& Student::operator=(Student&&)’
*__first = _GLIBCXX_MOVE(__val);
I searched earlier which helped me get to the result of adding a '<' overload, though I still get an error. Can anyone help point out where the mistake is? Thank you. (I compile using g++ --std=c++11)
the member variable const int num_courses_; is const, which means it must be set in the initializer list of the constructor.
num_courses_ can't be set by the copy assignment operator Student& Student::operator=(Student&&), so it prevent the compiler from generating the copy assignment operator for that class. Since there's no copy assignment operator available, and the std::sort function needs it to work, the compilation fails and complains about the copy assignment operator not being available.
Simply remove the const and declare the variable as int num_courses_ and your code should work.
Related
I cannot understand, as the both cases look so similar, in first for_each i cannot get reference to pair, and in second I get the reference to pair with no fuss. Could anybody please explain it to me?
#include <unordered_map>
#include <cstring>
#include <algorithm>
#include <iostream>
struct table_info_t {
char name[32] = {0};
int posx;
int posy;
table_info_t(const char *name, int posx, int posy) : posx(posx), posy(posy) {
strncpy(this->name, name, 31);
}
};
struct point {
int posx;
int posy;
point(int posx, int posy) : posx(posx), posy(posy) { }
};
size_t hashstruct(const char* hptr, size_t size) {
size_t h = 31;
for (size_t i = 0; i < size; i++) {
h = (h + *hptr) * 31;
hptr++;
}
return h;
}
#define MAP_OPERATORS(typ)\
namespace std {\
\
template<>\
struct hash<typ> {\
std::size_t operator()(const typ &k) const { return hashstruct((const char*)&k, sizeof(typ)); }\
};\
\
bool operator==(const typ& one, const typ& other) { return memcmp(&one, &other, sizeof(typ)) == 0; }\
};
MAP_OPERATORS(point); //hash structure and operator==
MAP_OPERATORS(table_info_t); //hash structure and operator==
int main(int argc, char** argv) {
std::unordered_map<point, int> sp;
sp[point(3, 4)] = 7;
std::for_each(sp.begin(), sp.end(),
[](std::pair<point, int> pair) {
std::cout << pair.first.posx << "+" <<pair.first.posy << "=" << pair.second << "\n";
});
std::unordered_map<table_info_t, const char *> m;
m[table_info_t("make my day", 3, 14)] = "make my day 3,14";
std::for_each(m.begin(), m.end(),
[](std::pair<const table_info_t, const char * >& pair)
{
std::cout << pair.first.name << pair.first.posx << pair.first.posy << " " << pair.second << "\n";
}
);
return 0;
}
Both structures do not differ so much, but when compiling this, I get this error:
In file included from .../4.8.2/include/c++/4.8.2/algorithm:62:0,
from .../src/main/c/hashtable.cpp:10:
.../4.8.2/include/c++/4.8.2/bits/stl_algo.h: In instantiation of '_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = std::__detail::_Node_iterator<std::pair<const point, int>, false, true>; _Funct = main(int, char**)::__lambda0]':
.../src/main/c/hashtable.cpp:45:24: required from here
.../4.8.2/include/c++/4.8.2/bits/stl_algo.h:4417:14: error: no match for call to '(main(int, char**)::__lambda0) (std::pair<const point, int>&)'
__f(*__first);
^
.../src/main/c/hashtable.cpp:43:24: note: candidates are:
[](std::pair<point, int> &pair) {
^
In file included from .../4.8.2/include/c++/4.8.2/algorithm:62:0,
from .../src/main/c/hashtable.cpp:10:
.../4.8.2/include/c++/4.8.2/bits/stl_algo.h:4417:14: note: void (*)(std::pair<point, int>&) <conversion>
__f(*__first);
^
.../4.8.2/include/c++/4.8.2/bits/stl_algo.h:4417:14: note: candidate expects 2 arguments, 2 provided
.../src/main/c/hashtable.cpp:43:53: note: main(int, char**)::__lambda0
[](std::pair<point, int> &pair) {
^
.../src/main/c/hashtable.cpp:43:53: note: no known conversion for argument 1 from 'std::pair<const point, int>' to 'std::pair<point, int>&'
and I need to remove the reference. However reference to pair<const table_info_t, const char * > is perfectly fine for the compiler in second for_each.
When you iterate over std::unordered_map<Key, Value>,
you iterate on std::pair<const KEY, VALUE>
In the second case, you take std::pair<const KEY, VALUE>& so it is fine.
You might even add const as you don't change the pair: const std::pair<const KEY, VALUE>&.
In the first case, you use another type std::pair<KEY, VALUE>&.
std::pair<KEY, VALUE> can be constructed from std::pair<const KEY, VALUE>. However, a temporary can not be bound to non-const lvalue-reference. So using std::pair<KEY, VALUE>& is invalid. Using std::pair<KEY, VALUE> is valid but does extra copies. See unexpected copies with foreach over a map for details.
If you have access to C++14, you may simplify it using a generic lambda:
[](const auto& p) {
std::cout << p.first.posx << "+" << p.first.posy << "=" << p.second << "\n";
});
In addition std::for_each can also be replaced by a range-based for loop (even in C++11):
for(const auto& p : sp) {
std::cout << p.first.posx << "+" << p.first.posy << "=" << p.second << "\n";
};
I am not a professional c++ programmer. I have tried to write a program to display all possible permutations of a given input string assuming if the string contains duplicate characters. This the code I have written so far:
Latest update of my code (permutation.cpp):
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <list>
#include <set>
#include <iterator>
#include <sstream>
#include <cstdlib>
using namespace std;
//factorial function
int factorial(int n){
if (n==0) return 1;
else{
return n*factorial(n-1);
}
}
int main (int argc, char *argv[]) {
srand ( time(NULL) ); //initialize the random seed
char* text;
std::set<char> mySwapList;
if ( argc < 1 )
{
cout << endl << "Please write a word in the following of the command line" << endl << endl;
return 1;
}
else if ( argc != 2 ) // argc should be 2 for correct execution
{ // We print argv[0] assuming it is the program name
strcpy (text,argv[1]);
cout<<endl<<"usage: "<< argv[0] <<" to compute all the permutations \n"<<endl;
return 1;
}
int ss=sizeof(text);
int length = ss;
int k=0;
cout << "length of the word:"<<endl<< length<<endl;
int total=factorial(length);
while (k< total)
{
char arr[ss];
int index=0;
stringstream ssin(text);
while (ssin.good() && index<ss){
ssin>>arr[index];
++index;
}
std::list<char> word(arr, arr+ss);
std::list<char> mylist;
unsigned int j=0;
while (j < length)
{
int n=word.size();
int RandIndex = rand() % n;
std::list<char>::iterator vi= word.begin();
std::advance(vi,RandIndex);
std::list<char>::iterator iter= mylist.begin();
mylist.insert(iter,*vi);
word.remove(*vi);
j++;
}
char str[ss];
int ii=0;
for (std::list<char>::iterator ix=mylist.begin(); ix!=mylist.end(); ++ix)
{
str[ii]=*ix;
ii++;
}
string newWord = string(str);
for (std::set<char>::iterator iss=mySwapList.begin(); iss!=mySwapList.end(); ++iss)
{
string w(1,*iss);
if (newWord != w)
{
mySwapList.insert(newWord);
k++;
}
}
}
//Loop for printing the list
for(std::set<char>::iterator it = mySwapList.begin(); it != mySwapList.end(); ++it)
cout << *it << " ";
cout << endl;
return 0;
}
I get a a good deal of error messages when I compile the code, including:
Updated errors:
permutation.cpp: In function ‘int main(int, char**)’:
permutation.cpp:82:39: error: no matching function for call to ‘std::set<char>::insert(std::string&)’
mySwapList.insert(newWord);
^
permutation.cpp:82:39: note: candidates are:
In file included from /usr/include/c++/4.8/set:61:0,
from permutation.cpp:9:
/usr/include/c++/4.8/bits/stl_set.h:460:7: note: std::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(const value_type&) [with _Key = char; _Compare = std::less<char>; _Alloc = std::allocator<char>; typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator = std::_Rb_tree_const_iterator<char>; std::set<_Key, _Compare, _Alloc>::value_type = char]
insert(const value_type& __x)
^
/usr/include/c++/4.8/bits/stl_set.h:460:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const value_type& {aka const char&}’
/usr/include/c++/4.8/bits/stl_set.h:497:7: note: std::set<_Key, _Compare, _Alloc>::iterator std::set<_Key, _Compare, _Alloc>::insert(std::set<_Key, _Compare, _Alloc>::const_iterator, const value_type&) [with _Key = char; _Compare = std::less<char>; _Alloc = std::allocator<char>; std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<char>; std::set<_Key, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<char>; std::set<_Key, _Compare, _Alloc>::value_type = char]
insert(const_iterator __position, const value_type& __x)
^
/usr/include/c++/4.8/bits/stl_set.h:497:7: note: candidate expects 2 arguments, 1 provided
/usr/include/c++/4.8/bits/stl_set.h:517:2: note: template<class _InputIterator> void std::set<_Key, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = _InputIterator; _Key = char; _Compare = std::less<char>; _Alloc = std::allocator<char>]
insert(_InputIterator __first, _InputIterator __last)
^
/usr/include/c++/4.8/bits/stl_set.h:517:2: note: template argument deduction/substitution failed:
permutation.cpp:82:39: note: candidate expects 2 arguments, 1 provided
mySwapList.insert(newWord);
I can not figure out why I got the above errors. Any suggestion?
Based on the question title you want to convert string to list.
You can't do it directly but you can use string iterator:
#include <string>
#include <list>
int main(int argc, _TCHAR* argv[])
{
std::string strTest = "hello!";
std::list<char> list(strTest.begin(), strTest.end());
return 0;
}
Edit: But based on your code you don't need list at all. You can use std::string everywhere. It has insert and [] stuff. It is almost the same as vector<char> but with additional functionality.
You used undefined class members.
Try strcpy_s() to char* arrays.
Using vector as a container for strings at the end of the code for mySwapList solves the problem of accepting strings as well as being easy to access each component of the vector. Here is the debugged and working version of the original question:
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <list>
#include <set>
#include <iterator>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
using std::vector;
//factorial function
int factorial(int n){
if (n==0) return 1;
else{
return n*factorial(n-1);
}
}
int main () {
srand ( time(NULL) ); //initialize the random seed
std::string text;
vector<std::string> mySwapList;
std::ostream_iterator<char> output(cout," ");
cout << endl << "Please write a word in the following of the command line" << endl << endl;
cin >>text;
int ss=text.size();
int k=0;
cout << "length of the word:" << endl << ss<<endl<<"input value:\n" <<text<< endl;
int total=factorial(ss);
cout << "The number of final permutations :\n"<<total<<endl;
while (k< total)
{
char arr[ss];
int index=0;
stringstream ssin(text);
while (ssin.good() && index<ss){
ssin>>arr[index];
++index;
}
std::list<char> word;
//insert items from arr into word list
word.insert(word.begin(),arr, arr+ss);
//A tool to print lists
cout<<"word contains:\n "<<endl;
std::copy(word.begin(),word.end(),output);
cout << endl;
std::list<char> mylist;
unsigned int j=0;
while (j < ss)
{
int n=word.size();
int RandIndex = rand() % n;
std::list<char>::iterator vi= word.begin();
std::advance(vi,RandIndex);
word.erase(vi);
std::list<char>::iterator iter= mylist.begin();
mylist.insert(iter,*vi);
j++;
}
cout << "constructed permuted word:"<<endl;
std::copy(mylist.begin(),mylist.end(),output);
cout << endl;
char str[ss];
str[ss]='\0';
int ii=0;
for (std::list<char>::iterator ix=mylist.begin(); ix!=mylist.end(); ++ix)
{
str[ii]=*ix;
ii++;
}
string newWord = string(str);
cout << "New Word :"<< endl << newWord <<" size of string:\n"<< (sizeof(str)/sizeof(*str)) << endl;
if (k==0)
{
mySwapList.push_back(newWord);
k++;
}
else
{
int flag=0;
for (int i=0;i<mySwapList.size();i++)
{
if (mySwapList[i]==newWord)
flag=1;
}
if (flag!=1)
{
mySwapList.push_back(newWord);
k++;
}
}
}
//Loop for printing the vector mySwapList
for(unsigned int i=0; i<mySwapList.size();i++)
cout << mySwapList[i] << " ";
cout << endl;
return 0;
}
This question already has answers here:
problems with c++ set container
(2 answers)
Closed 6 years ago.
I can't understand why g++ returns error like this:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h: In function 鈥榖ool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) [with _T1 = int, _T2 = stop]鈥
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:227: instantiated from 鈥榖ool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = std::pair<int, stop>]鈥
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tree.h:921: instantiated from 鈥榮td::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::insert_unique(const _Val&) [with _Key = std::pair<int, stop>, _Val = std::pair<int, stop>, _KeyOfValue = std::_Identity<std::pair<int, stop> >, _Compare = std::less<std::pair<int, stop> >, _Alloc = std::allocator<std::pair<int, stop> >]鈥
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_set.h:321: instantiated from 鈥榮td::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(const _Key&) [with _Key = std::pair<int, stop>, _Compare = std::less<std::pair<int, stop> >, _Alloc = std::allocator<std::pair<int, stop> >]鈥
newGraph.cpp:48: instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h:104: error: no match for 鈥榦perator<鈥in 鈥榑_x->std::pair<int, stop>::second < __y->std::pair<int, stop>::second鈥
Here is my code:
#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <set>
#include <utility> // for pair
#include <algorithm>
#include <iterator>
const int max_weight = INT_MAX;
struct stop {
std::string name_stop;
int id_stop;
bool operator !=(const stop &rhs) const
{
return ((id_stop != rhs.id_stop) || (name_stop != rhs.name_stop));
}
};
struct neighbor {
stop target;
int weight;
neighbor(stop arg_target, int arg_weight) : target(arg_target), weight(arg_weight) { }
};
std::list<stop> dijkstraComputeAndGetShortestPaths(stop src,
stop dst,
std::vector< std::vector<neighbor> > &adj_list,
std::vector<int> &min_distance,
std::vector<stop> &previous)
{
stop fake_stop;
fake_stop.id_stop = INT_MAX;
fake_stop.name_stop = "Null";
std::list<stop> path;
int n = adj_list.size();
min_distance.clear();
min_distance.resize(n, max_weight);
min_distance[src.id_stop] = 0;
previous.clear();
previous.resize(n, fake_stop);
std::set< std::pair< int, stop > > vertex_queue;
vertex_queue.insert(std::make_pair(min_distance[src.id_stop], src));
while (!vertex_queue.empty())
{
int dist = vertex_queue.begin()->first;
stop u = vertex_queue.begin()->second;
vertex_queue.erase(vertex_queue.begin());
// Visit each edge exiting u
const std::vector<neighbor> &neighbors = adj_list[u.id_stop];
for(std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();
neighbor_iter != neighbors.end();
neighbor_iter++)
{
stop v = neighbor_iter->target;
int weight = neighbor_iter->weight;
int distance_through_u = dist + weight;
if (distance_through_u < min_distance[v.id_stop]) {
vertex_queue.erase(std::make_pair(min_distance[v.id_stop], v));
min_distance[v.id_stop] = distance_through_u;
previous[v.id_stop] = u;
vertex_queue.insert(std::make_pair(min_distance[v.id_stop], v));
}
}
if(u.id_stop == dst.id_stop)
{
std::cout << "Find : ";
for ( ; dst != fake_stop; dst = previous[dst.id_stop])
{
path.push_front(dst);
}
return path;
}
}
}
int main()
{
std::vector< std::vector<neighbor> > adj_list(9);
stop stop_s;
stop_s.id_stop = 1001;
stop_s.name_stop = "A";
stop stop_x;
stop_x.id_stop = 1002;
stop_x.name_stop = "B";
adj_list[stop_s.id_stop].push_back(neighbor(stop_x, 5));
stop_s.id_stop = 1003;
stop_s.name_stop = "C";
adj_list[stop_x.id_stop].push_back(neighbor(stop_s, 15));
stop_x.id_stop = 1004;
stop_x.name_stop = "D";
adj_list[stop_s.id_stop].push_back(neighbor(stop_x, 20));
stop_s.id_stop = 1001;
stop_s.name_stop = "A";
std::vector<int> min_distance;
std::vector<stop> previous;
std::list<stop> path = dijkstraComputeAndGetShortestPaths(stop_s, stop_x, adj_list, min_distance, previous);
std::cout << "Distance from 1001 to 1004: " << min_distance[stop_x.id_stop] << std::endl;
//std::cout << "Path : ";
#if 0
for (int index = 0; index < path.size(); index++)
{
auto path_front = path.begin();
std::advance(path_front, index);
std::cout << path_front->id_stop << " ";
}
std::cout << std::endl;
#endif
return 0;
}
std::set require you to specify an operator < for the type it holds or you can supply your own comparison functor as a template parameter. Since stop does not have an operator < the operator < from std::pair is not compileable since it relies on using the operator < of the types it holds.. You either need to supply your own comparison functor or define an operator < for stop.
I want to make a class that stores strings from the console in a vector and then sorts them alphabetically using selection sort.
This is my code so far.
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class Dictionary
{
public:
Dictionary();
void read(vector<int>&words);
void SelectionSort(vector <int> &num);
private:
//vector<string> line_vector;
string word;
//vector<string> words;
};
Dictionary:: Dictionary()
{
//line_vector = "<empty>";
string word = "<empty>";
}
void Dictionary:: read(vector<int>& words)
{
//vector<string> words;
string word;
while( cin >> word ) words.push_back(word);
}
////////////////////////////////////////////////////////////////////////////////////
void Dictionary:: SelectionSort(vector <int> &num)
{
int i, j, first, temp;
int numLength = num.size( );
for (i= numLength - 1; i > 0; i--)
{
first = 0; // initialize to subscript of first element
for (j=1; j<=i; j++) // locate smallest between positions 1 and i.
{
if (num[j] < num[first])
first = j;
}
temp = num[first]; // Swap smallest found with element in position i.
num[first] = num[i];
num[i] = temp;
}
return;
}
void print(vector<Dictionary>& a)
{
for (int i = 0; i < a.size(); i++)
cout << a[i];
cout << "\n";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
Dictionary dict;
vector<Dictionary> str;
dict.read(str);
dict.SelectionSort(str);
dict.print(str);
return 0;
}
and these are the errors:
In member function 'void Dictionary::read(std::vector<int>&)':
31:46: error: no matching function for call to 'std::vector<int>::push_back(std::string&)'
31:46: note: candidates are:
In file included from /usr/include/c++/4.9/vector:64:0,
from 3:
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]
push_back(const value_type& __x)
^
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note: no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const value_type& {aka const int&}'
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]
push_back(value_type&& __x)
^
One of the error lines seems very helpful:
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note:
no known conversion for argument 1
from
'std::string {aka std::basic_string<char>}'
to
'const value_type& {aka const int&}'
If you pass an argument that doesn't match the expected type for a function, then C++ will try to find any conversion from the passed type into the expected type. The conversion include 1-argument constructors and cast operators. See http://www.cplusplus.com/doc/tutorial/typecasting/
This particular error is indicating that the passed argument cannot be converted to an int.
So I was writing an algorithm for a TopCoder problem and I got the following errors. I have tried my best to eliminate syntax errors but I can't seem to figure out what is warranting these errors. Can you help me out with it? I am not very experienced and I'm trying to learn.
tc1.cpp: In member function ‘std::vector<std::basic_string<char> > BinaryCode::decode(std::string)’:
tc1.cpp:46:20: error: no matching function for call to ‘std::vector<std::basic_string<char> >::push_back(std::stringstream&)’
tc1.cpp:46:20: note: candidate is:
/usr/include/c++/4.6/bits/stl_vector.h:826:7: note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::basic_string<char>, _Alloc = std::allocator<std::basic_string<char> >, std::vector<_Tp, _Alloc>::value_type = std::basic_string<char>]
/usr/include/c++/4.6/bits/stl_vector.h:826:7: note: no known conversion for argument 1 from ‘std::stringstream {aka std::basic_stringstream<char>}’ to ‘const value_type& {aka const std::basic_string<char>&}’
make: *** [tc1] Error 1
The code I've written is -
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
class BinaryCode
{
public:
vector<string> decode(string message)
{
int cntrl = 0;
vector<string> P;
bool poss = true;
int a = message.length();
int A[a+2], B[a+2];
for (int i=1; i<=a ; i++)
{
stringstream ss(message.substr(i,1));
ss >> B[i];
}
while (cntrl <2)
{
A[0] = A[a+1] = cntrl;
for (int i=0; i<=a; i++)
{
A[1] = B[2] - cntrl;
A[i+1] = B[i] - A[i] - A[i-1];
if (A[i+1]<0 || A[i+1])
{
poss = false;
}
}
if (!poss)
P.push_back("NONE");
else
{
stringstream s;
for (int i =0; i<a+2; i++)
s << (char)A[i];
P.push_back(s);
}
cntrl++;
}
return P;
}
};
int main()
{
BinaryCode ob;
string str;
cout << "Enter the encrypted string: " << endl;
cin >> str;
vector<string> vec = ob.BinaryCode::decode(str);
vector<string>::iterator it = vec.begin();
for (; it!= vec.end(); it++) {
cout << *it;
}
}
I'd be grateful if someone could point out what I'm doing wrong with this.
You are pushing a stringstream into a vector of strings. Change
P.push_back(s);
to
P.push_back(s.str());