How to traverse a char among the vector elements? - c++

enter image description here
Is there any built-in function that exists to allow programmers to find a single char in a string vector(elements)?

There is no built-in function that checks for a character in a string among a vector of strings.
However, there are built-in functions for various sub-tasks involved in the process, which you can adjoin together to achieve your goal.
A simple way to achieve what you want would be to iterate over the vector of strings and use std::find() on each string to search for the element you desire:
#include <iostream>
#include <vector>
int main()
{ std::vector<std::string> s;
s.push_back("Stack");
s.push_back("Overflow");
char c;
std::cin>>c;
for(std::string& e:s)
{
if(e.find(c))
{ std::cout<<"found";
break;
}
}
return 0;
}

Related

Merging two sorted vectors in one sorted vector

Background: General Goal take two sorted files with strings separated by white space, and bring them together in to one sorted file.
Current Goal, to see if i can use the merge function or a similar function to combine two sorted vectors.
I was using http://www.cplusplus.com/reference/algorithm/merge/, to guide my use of the function merge. However, I get the error "No matching function call to 'merge'".
I'm not sure if the merge function will actually do what I am wanting with strings, but I trying to use it to see if it does.
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm> // std::merge, std::sort
#include <string>
using namespace std;
ifstream r_data_file(const string oname)
{
ifstream ist {oname};
if (!ist) {
string error = "cannot open " + oname;
throw runtime_error(error);
}
return ist;
}
void get_words(ifstream& ist, vector<string>& Po)
{
for (string p; ist >> p;) {
Po.push_back(p);
}
}
int main ()
{
vector<string> file1;
vector<string> file2;
ifstream ist = r_data_file("wordlist_1.txt");
get_words(ist, file1);
ifstream ist_2 = r_data_file("wordlist_2.txt");
get_words(ist_2, file2);
vector<string> file_1n2(file1.size()+file2.size());
merge(file1, file1.end(), file2, file2.end(), file_1n2);
}
I would appreciate your thoughts, cheers!
You cannot simply use file1, file2 and file_1n2 as simple pointers(maybe your confusion comes because you use plain arrays in that way). Here merge uses stl iterators, not just a pointer. To fix the problem, use:
merge(file1.begin(), file1.end(), file2.begin(), file2.end(), file_1n2.begin());

Storing a string into a vector

The error says that no matching function to call for push_back().
I included <vector> so I don't understand why this error is occurring. If you could also show me how to take in a string and store it into a vector that would be really helpful!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> list;
char input;
while(cin>>input)
{
list.push_back(input);
}
for(int i=0;list.size();i--)
{
cout<<list[99-i];
}
}
Since your list is a vector of string, pushing single chars into it wouldn't work: you should either make it a vector of chars, or read strings:
string input;
while(cin>>input) {
list.push_back(input);
}
Note that list[99-i] is rather suspicious: it will work only if the list has exactly 99 elements, and only if you change i-- for i++. Otherwise, you would get undefined behavior either on accessing elements past the end of the vector, or accessing elements at negative indexes.
If you would like to print the list from the back, use list[list.size()-1-i] instead, and use i++ instead of i--, because otherwise the loop would not stop.
Well, the error is correct. It helps, though, to read all of it!
The class vector<string> has a function push_back(const string&).
It does not have a function push_back(char).
I don't know why you're extracting individual chars but storing whole strings; don't do that.
Because you are trying to put in char into a string vector.
Change input to string.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
string v;
vector<string> s;
for(int i=0;i<n;i++)
{
cin>>v;
s.push_back(v);
}
sort(s.begin(),s.end());
for(int i=0;i<n;i++)
{
cout<<s[i]<<endl;;
}
return 0;
}

Trouble using find function in C++

I am trying to find the difference in my code when I use std::find.
For my test code. I made a Vector called Test
std::vector<const char*> Test;
To test the find function, I filled the Test vector with dummy data by using push_back function
Test.push_back("F_S");
Test.push_back("FC");
Test.push_back("ID");
Test.push_back("CD");
Test.push_back("CT");
Test.push_back("DS");
Test.push_back("CR");
Test.push_back("5K_2");
Test.push_back("10K_5");
Test.push_back("10K_1");
Test.push_back("10K_2");
Test.push_back("10K_3");
Test.push_back("10K_4");
Test.push_back("10K_5");
What I want to do with the find function is to go through the Test and see if there are any repeated data. The first time a encounter the data, I will save it to a vector called Unique_Data.
std::vector<const char*> Unique_Data;
So for the 14 data points above, only 13 will be saved because 10K_5 repeated.
The Code I am using looks like this
for(int i = 0; i < Test.size(); i++)
{
if( Unique_Data.empty())
{
Unique_Data.push_back(Test[i]);
}
else if (std::find(Unique_Data.begin(), Unique_Data.end(), Test[i]) != Unique_Data.end())
{
// Move on to next index
}
else
{
Unique_Data.push_back(Test[i]);
}
}
The problem I am having is when I am using the dummy data. I am getting a correct answer for Unique_Data.
However, if I save the actual data into the Test vector which are saved in linked list. I get that they are all unique.
The code looks like this
p_curr = List.p_root;
while(p_curr != NULL)
{
// id starts from 0
if(atoi(p_curr->id) == 14) break;
Test.push_back(p_curr->Descriptor);
p_curr = p_curr->p_next;
}
I tested with the same 14 data. They are all const char* types. However, when I used the linked list data. The find function thinks all the data is unique.
Can anyone tell me what is wrong with this?
Using C-style strings is a bit tricky, they are just a pointer, and pointers are compared by identity. Two C strings with the same sequence of characters, but different addresses will compare different.
const char first[] = "Hi";
const char second[] = "Hi";
assert(first == second); // will fail!
There are two solutions to this problem. The simple one is using std::string in your container, as std::string will provide value comparisons. The alternative is to pass a comparison functor to std::find as a last argument. But this will still leave the problem of managing the lifetime of the const char*-s stored in the vector.
This is a pointers problem. You're not storing strings in your array, you're storing the memory address of the data in the string.
This strange behaviour is probably because in your example case you have literal strings that cannot be changed, so the compiler is optimising the storage, and when two strings are the same then it stores the same address for all strings that have the same text.
In your real data example, you have a bunch of strings that hold the same data, but each of these strings lives at a different memory address, so the find function is saying that all strings have a different address.
In summary, your find function is looking at the memory address of the string, not the data (text) in the string. If you use std::strings then this problem will disappear.
I would highly recommend using strings, as performance is going to be more than good enough and they eliminate a vast number of problems.
As David Rodriguez mentions in his answer, you're only comparing pointers, and not the contents of the strings themselves. Your solution will work as is if you were storing std::strings instead of char const *. With the latter, you need to resort to std::find_if and a predicate that calls strcmp to determine whether the strings are identical.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
int main()
{
std::vector<const char*> Test;
Test.push_back("F_S");
Test.push_back("FC");
Test.push_back("ID");
Test.push_back("CD");
Test.push_back("CT");
Test.push_back("DS");
Test.push_back("CR");
Test.push_back("5K_2");
Test.push_back("10K_5");
Test.push_back("10K_1");
Test.push_back("10K_2");
Test.push_back("10K_3");
Test.push_back("10K_4");
Test.push_back("10K_5");
std::vector<const char*> Unique_Data;
for(auto const& s1 : Test) {
if(std::find_i(Unique_Data.cbegin(), Unique_Data.cend(),
[&](const char *s2) { return std::strcmp(s1, s2) == 0; })
== Unique_Data.cend()) {
Unique_Data.push_back(s1);
}
}
for(auto const& s : Unique_Data) {
std::cout << s << '\n';
}
}
Here's a live example

Reverse a word using function call

How can input a word and reverse the output of it. I made a function to calculate the length of the word and from here I have to reverse the word depending on the length of it.
How can I do that?
#include<iostream>
using std::cout;
using std::endl;
using std::cin;
int LengthOfString( const char *); // declaring prototype for length of the string
int reverse(const char []);
int main()
{
char string1[100];
cout<<"Enter a string: ";
cin>>string1;
cout<<"Length of string is "<<LengthOfString(string1);
system("PAUSE");
return 0;
}
int LengthOfString( const char *x)
{
int index;
for(index = 0; *x!='\0';x++,index++);
return index;
}
int reverse(const char y[])
{
/* my attempted loop, its not right i know.
a[] = *index; // length of the word
for(int i=0; i<=index/2; i++)
for(j=0; j == length, j--) */
}
This wheel has already been invented, and exists in the standard library.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string word;
std::cout << "Enter a word: ";
std::cin >> word;
std::reverse(word.begin(), word.end());
std::cout << "Reverse: " << word << std::endl;
return 0;
}
To understand exactly what's going on here, there are a few things that you must cover first:
data structures (classes)
containers
iterators
I hope you already know what a class is. In case you're still in introductory stuff, a class is basically a user defined collection of state and behavior. The author can choose to restrict access to the state or behavior of a class for a variety of reasons. In the case of std::string, the standard library string class, all of the state is hidden and only behavior is accessible.
The string class is a container that contains characters. There are numerous other container classes, each of which with different strengths and weaknesses. The string class contains a sequence of characters with a strict order. Other containers exist, such as std::set, std::vector, std::list, and others. std::string bears a passing resemblance to std::vector, and is a distant cousin of std::list. Each collection behaves differently and is suited for different things.
You might think you need to understand how the string class stores its data in order to reverse it, but you don't. This is where iterators come in. std::string owns a typedef, std::string::iterator, which is a special object which stores the location of a single element in a string. std::reverse is a library function which takes 2 iterators and repeatedly swaps their contents and moves them towards each other. This looks like this as it's happening:
v v <-- positions of iterators (start at the start, end at the end)
ABC <-- initial state
v v <-- the end iterator moved back
ABC
v v
CBA <-- the iterators swapped their values
vv <-- the begin iterator moved forward
CBA
V <-- the end iterator moved back; both iterators are in the same place
CBA <-- therefore, we're done, the string is reversed
One thing about iterators is they're kind of like pointers. In fact, you can pass pointers to some functions that expect iterators because they behave syntactically the same. Therefore, you should be able to write your own reverse function that uses pointers that basically does the same thing this did, except with char *s.
Here's some pseudocode that you should be able to write the function with (I won't write it out completely because it's homework):
namespace BaidNation
{
void reverse(char *begin, char *end)
{
loop forever
{
if (end equals begin):
done;
move end backwards;
if (end equals begin):
done;
swap end's and begin's characters;
move begin forwards;
}
}
}
Keep in mind that BaidNation::reverse (as well as std::reverse) expects for end the iterator that references the element AFTER the end of the collection, not the one that references the last element. How does it then make sense to use this?
Your LengthOfString function returns the number of non-null characters in a string. Since arrays are zero-indexed, we know that, like any other array, if we check string1 + LengthOfString(string1), we'll get a pointer to the character after the end which is, for once, exactly what we want.
Thus, we can use this to reverse the string:
BaidNation::reverse(string1, string1 + LengthOfString(string1));
If you have to use exactly the signature earlier, you can adapt this design into the other one:
int reverse(const char str[])
{
char *start = str, *end = str + LengthOfString(str);
BaidNation::reverse(start, end);
}
Based on the fact that the return type of your prototype function is int, it looks to me like you want to do an in-place reversal of a string. You first need to find out how long the string is (although you computed that before, you didn't pass the result to this function), then swap elements until you get to the middle. To make this work you need to pass, not a const char[], but just a char* (indicating that you will be changing the content):
int reverse(char* y)
{
int ii, n;
n = LengthOfString(y); // "no built in functions - otherwise, use strlen()
for(ii=0; ii<n/2;ii++) {
char temp;
temp = y[ii];
y[ii] = y[n - ii - 1];
y[n - ii] = temp;
}
}
Declare a new char* of the same length, and then loop as follows -
for(int i=0;i<stringLength;i++){
newString[i]=oldString[stringLength-i];
}
return newString;
Also you might want to consider using the String class instead of char*.

How can I sort a string using C++ library function or STL?

char word[100],p[100],result[4][100];
I want to sort the result[4][100] alphabetically. for example
result[0]="adbs";
result[1]="aacs";
result[2]="abef";
result[3]="abbm";
after sort it will be:
result[0]="aacs";
result[1]="abbm";
result[2]="abbm";
result[3]="adbs";
how can I do this using library function or STL. thanks in advance,
What about making result an array of std::string instead and sorting that:
std::string result[4];
std::sort(result, result + (sizeof(result) / sizeof(result[0])));
Mark B's answer is the C++ way to do things.
If you are stuck with the raw character arrays, you might be better off with a C-style approach.
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <iostream>
typedef int (*Comparator)(const void *, const void *);
int main() {
const std::size_t cWords = 4;
char result[cWords][100] = { "az", "ax", "aa", "ab" };
std::qsort(result, cWords, sizeof(result[0]),
reinterpret_cast<Comparator>(std::strcmp));
for (std::size_t i = 0; i < cWords; ++i) {
std::cout << result[i] << std::endl;
}
return 0;
}
The approach is essentially the same, but the details differ.
qsort takes void pointers, the type size, and a comparison function (that also uses void pointers) to implement a sort on any kind of data type.
std::sort uses templates to handle the type-specific details, so you can work at a higher level of abstraction and also get better type-safety. But this can be harder to get right when you don't have a real type but just a fixed-length character array. The std::sort approach can potentially be faster, since the compiler has the chance to inline the comparison function.