void Print(vector<string>) function is not printing [duplicate] - c++

This question already has answers here:
STL vector reserve() and copy()
(5 answers)
Closed 4 years ago.
I made a function for printing a vector using interators. The function is part of program meant to copy a vector of strings to another vector of strings. The original function was a simple for loop using the .at() member function and that worked. So, I am not sure what's wrong with this one.
The code:
#include <string>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(vector<string> &v);
int main() {
ifstream inFS;
inFS.open("sentence.txt");
vector<string> wordList; vector<string> newVect;
string s;
while (inFS >> s) {
wordList.push_back(s);
}
copy(wordList.begin(), wordList.end(), newVect.begin());
print(wordList);
print(newVect);
}
void print(vector<string> &v) {
for (vector<string>::iterator i = v.begin(); i != v.end(); i++) {
cout << *i << " ";
}
cout << endl;
}
The output:
C:\Users\westt\Documents\PROJECT>a.exe
C:\Users\westt\Documents\PROJECT>

Try this simple change to initialize the newVect. As the comment noted, you could also resize() newVect
#include <string>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(vector<string> &v);
int main() {
ifstream inFS;
inFS.open("sentence.txt");
vector<string> wordList;
string s;
while (inFS >> s) {
wordList.push_back(s);
}
vector<string> newVect(wordList);
print(wordList);
print(newVect);
}
void print(vector<string> &v) {
for (vector<string>::iterator i = v.begin(); i != v.end(); i++) {
cout << *i << " ";
}
cout << endl;
}

Related

Vectors and Strings C++

#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main()
{
vector<string> test;
test.push_back("yasir");
test.push_back("javed");
for(int i=0; i!=test.end();i++)
{
cout << test[i];
}
}
Why is this code giving up an error? I am unable to identify the cause of the error.
Error: No Match for operator !=....
First of all, you are trying to compare int with the iterator of vector.
for(int i=0; i!=test.end();i++)
{
cout << test[i];
}
Here, the test.end() returns the iterator. There is no overloaded operator!= which can compare integer (int i = 0) with that iterator (test.end()).
So your loop should look more like:
for (std::vector<string>::iterator i = test.begin(); i != test.end(); i++)
{
cout << *i;
}
You can replace std::vector<string>::iterator with auto, if using C++11 or newer.
The next thing, you included <string.h> which contains old functions such as: strlen, strcpy. Similarly, <cstring> contains C-style strings.
If you want to you use operator<<, so if you want to write:cout << then you have to do: #include <string>.
As already mentioned, the problem is, that you try to compare an integer with an iterator in the "middle" of your for statement. Try this instead, it's more intuitive from my point of view
#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main()
{
vector<string> test;
test.push_back("yasir");
test.push_back("javed");
for(int i=0; i<test.size();++i)
{
cout << test[i];
}
}

Sort a Substring in Descending order using Vector, however getting segmentation fault

I want to sort the string from N to M where N indicates the starting index and M indicates the ending index.
However, my code is getting failed with segmentation fault.
Here is my code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s;
int M=0,N=0;
cout<<"Enter String"<<endl;
getline(cin,s);
vector<char> data(s.begin(), s.end());
cout<<"Enter start_index and end_index for sorting";
cin>>N>>M; //Passed externally as N=start_index, M=end_index
std::sort(data.begin()+N, data.begin()+M, std::greater<char>());
for (std::vector<char>::const_iterator i = data.begin(); i != data.end(); ++i)
std::cout << *i << ' ';
return 0;
}
This example does work fine for me:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s = "ABCDEFG";
int N = 1;
int M = 5;
vector<char> data(s.begin(), s.end());
std::sort(data.begin() + N, data.begin() + M, std::greater<char>());
for (auto& character : data)
std::cout << character << ' ';
return 0;
}
http://coliru.stacked-crooked.com/a/ee7c5f05afe85115
I suspect you get an empty string with cin, and therefore your data.begin() is invalid.
Be cautious with user entered data. Always do proper checking for input that may break your code.
Additonally your templated greater is the comparing function for the wrong type.
The answer to the above question is from the guidance of Trevir.
In order to avoid the segmentation fault, check the size of the input
string and then apply operations on it.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s;
int M,N;
cout<<"Enter String"<<endl;
getline(cin,s);
if ( s.size() == 0 )
{
std::cout << "Empty Input" << std::endl;
return 0;
}
vector<char> data(s.begin(), s.end());
cout<<"Enter start_index and end_index for sorting";
cin>>N>>M; //Passed externally as N=start_index, M=end_index
std::sort(data.begin()+N, data.begin()+M, std::greater<char>());
for (std::vector<char>::const_iterator i = data.begin(); i != data.end(); ++i)
std::cout << *i;
return 0;
}

replacing a string in a vector without positioning

In the code i am working on now I have a vector load itself from a txt file now I was trying to see if their was a way to replace certain words in the vector without needing a position or anything
so for example if the txt contained a list of animals and i wanted to change bird to book how would i do that without need the position of the letters
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
vector <string> test;
int main()
{
string file;
fstream fout( "Vector.txt" );
while ( !fout.eof())
{
getline(fout,file);
test.push_back(file);
}
fout.close();
for( int i = 0; i < test.size(); i++)
{
cout << test[i] << endl;
}
system("pause");
}
txt contains:
dog
cat
bird
hippo
wolf
Use std::transform().
std::string bird2book(const string &str)
{
if (str == "bird")
return "book";
return str;
}
std::transform(test.begin(), test.end(), test.begin(), bird2book);
you can use std::replace
std::replace (test.begin(), test.end(), "bird", "book");
Try this:
typedef std::istream_iterator<string> isitr;
ifstream fin("Vector.txt");
vector <string> test{ isitr{fin}, isitr{} }; // vector contains strings
map<string,string> dict{ // replacements dictionary
{"bird", "book"}, {"cat", "kitten"}
};
for(auto& x: test) // x must be a reference
{
auto itr = dict.find(x);
if(itr != dict.end()) // if a match was found
x = itr->second; // replace x with the found replacement
// (this is why x must be a reference)
}
for(const auto& x: test)
cout << test << " ";
Use STL!! It's our power. Everything you need:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include <fstream>
#include <map>
int main()
{
std::vector<std::string> words;
const std::map<std::string, std::string> words_to_replace{
{ "bird", "book" }, { "cat", "table" }
};
auto end = words_to_replace.cend();
std::transform(
std::istream_iterator<std::string>{ std::ifstream{ "file.txt" } },
std::istream_iterator<std::string>(),
std::back_inserter(words),
[&](const std::string& word) {
auto word_pos = words_to_replace.find(word);
return (word_pos != end) ? word_pos->second : word;
});
std::copy(words.cbegin(), words.cend(),
std::ostream_iterator<std::string>(std::cout, "\n"));
std::cout << std::endl;
}

C++; Using strings getline() not working with file input

I can get getline() to work with cin (getline(cin,line)), but when I open a stream, it won't read the line from the file. The file contains a list of elements from the periodic table.
for Example:
H
He
O
etc...
EDIT:
However, when I try to cout the newly read line, it doesn't put it into var symbol at the line:
cout << "symbol: " << symbol << endl;
It doesn't give me anything out, but it should return the first element (H).
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void print(vector <string> x)
{
cout << "list of elements:" << endl;
for (int i = 0; i < x.size(); ++i)
{
cout << x[i] << endl;
}
}
int main(int argc, char** argv)
{
string symbol;
vector <string> elementlist;
ifstream readin;
readin.open("Elements.txt");
getline(readin,symbol);
cout << "symbol: " << symbol << endl;
while (!readin.good())
{
elementlist.push_back(symbol);
getline(readin,symbol);
}
print (elementlist);
return 0;
}
I'd do it something like this:
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
class line {
std::string data;
public:
friend std::istream &operator>>(std::istream &is, line &l) {
std::getline(is, l.data);
return is;
}
operator std::string() const { return data; }
};
int main() {
std::ifstream readin("Elements.txt");
// Initialize vector from data in stream:
//
std::vector<std::string>
element_list((std::istream_iterator<line>(readin)),
std::istream_iterator<line>());
// write data from vector to cout:
//
std::copy(element_list.begin(), element_list.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
As I stated in my comment, your loop condition is wrong.
while (!readin.good())
{
elementlist.push_back(symbol);
getline(readin,symbol);
}
As it turns out, you want to loop using the condition readin.good(). Since !readin.good() will evaluate to false, you never actually enter the loop.

C++ sort array of strings

I am trying to sort an array of strings, but it's not sorting anything.... what am I doing wrong?
string namesS[MAX_NAMES];
int compare (const void * a, const void * b){
return ( *(char*)a - *(char*)b );
}
void sortNames(){
qsort(namesS, MAX_NAMES, sizeof(string), compare);
}
This is C++, not C. Sorting an array of strings is easy.
#include <string>
#include <vector>
#include <algorithm>
std::vector<std::string> stringarray;
std::sort(stringarray.begin(), stringarray.end());
std::qsort is inherited from the standard C library. It will not work.
You need to use std::sort for sorting strings.
Specifically, cast std::string to void* and then to char* is undefined and won't work.
algorithm sort in CPP has the same complexity as qsort:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
bool compare(string a, string b){
cout << "compare(" << a << "," << b << ")" << endl;
return (a.compare(b) < 0);
}
int main () {
string mystrs[] = {"www","ggg","bbb","ssss","aaa"};
vector<string> myvector (mystrs, mystrs + 5);
vector<string>::iterator it;
sort (myvector.begin(), myvector.end(), compare);
cout << "vector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
You can use boost::sort, like this:
#include <vector>
#include <boost/range/algorithm.hpp>
std::vector<std::string> stringarray;
boost::sort(stringarray);
If you want use find use boost::find, like this:
std::string findme;
auto offset = boost::find(stringarray, findme) - stringarray.begin()
See 2 useful functions (m_stringarray should be member of ClassA):
const size_t ClassA::GetIdByName(std::string name) const
{
return (boost::find(this->m_stringarray, name) - this->m_stringarray.begin());
}
const std::string ClassA::GetNameById(size_t id) const
{
return this->m_stringarray[id];
}
As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful
bool cmp(string a, string b)
{
if(a.compare(b) > 0)
return true;
else
return false;
}
int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);
for(int i = 0; i < length; i++)
cout << words[i] << " ";
cout << endl;
// output will be: this test is a
}
If you want to reverse the order of sorting just modify the sign in the cmp function.
Here is C++ another way to sort array of string without using <vector>.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string WordArray[] = {"AA","DD","CC","BB","ZZ","NN"};
sort(begin(WordArray), end(WordArray)); /*Sort the Array*/
for(auto& Word: WordArray){
cout<<Word<<endl; /*Print Every String Element*/
}
return 0;
}