i know my question can be stupid for somebody, but i googled all day and try make my own solution but i failed.. Please help..
I need print all uniqe string from an simple array of strings.
example:
input: "Hi" "my" "name" "Hi" "potato" "text" "name" "Hi"
output: "my" "potato" "text"
I make just function to print everything once ("Hi", "my", "name", "potato", "text"), but i need ignore everything what is 2x and more times in array.
My algorythm was:
1. sort by bubblesort
print only last string from sorted sequence by using basic for and if
.. if(array[i]!=array[i+1]) //make something...
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<std::string> v = {
"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi",
};
sort(v.begin(), v.end());
for (auto a = v.begin(), b = a; a != v.end(); a = b) {
b = find_if(b, v.end(), [&](string s) {return *b != s;});
if (distance(a, b) == 1)
cout << *a << '\n';
}
}
update : i was misunderstanding the question now it works as output in the question
simply you can count the occurrences of every string and print only strings which occur ones..
time complexity : O(N^2)
here is the code
#include<iostream>
#include<set>
#include <string>
#include <vector>
using namespace std;
int main()
{
int n; // number of strings you want in your array
cin >> n;
string t; // get t and push back it in the vector
vector <string> words; //we use vector to store as we will push back them
for(size_t i = 1;i <= n;i++)
{
cin >> t;
words.push_back(t);
}
for(int i = 0;i < words.size();i++)
{
int cnt = 0;
for(int j = 0;j < words.size() && cnt < 2;j++)
{
if(words[i] == words[j])
cnt++;
}
if(cnt == 1) //its unique..print it
cout << words[i] <<endl;
}
}
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi"};
std::sort(words.begin(), words.end());
for (auto curr = words.begin(); curr != words.end(); ) {
// If working w/ few duplicate words:
auto next = std::find_if(
curr + 1, words.end(), [&](const auto& s) { return s != *curr; }
);
/* If working w/ many duplicate words:
auto next = std::upper_bound(curr + 1, words.end(), *curr); */
if (std::distance(curr, next) == 1) {
std::cout << *curr++ << '\n';
} else {
curr = next;
}
}
}
Demo
std::sort, std::upper_bound, std::find_if, std::distance
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi"};
std::vector<std::string> out;
std::sort(words.begin(), words.end());
std::unique_copy(words.begin(), words.end(), std::back_inserter(out));
std::set_difference(words.begin(), words.end(), out.begin(), out.end(), std::ostream_iterator<std::string>(std::cout, " "));
}
Note: Not tested as I am writing this on my phone and in bed.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,j;
string ss;
cin>>ss;
for(i=0;i<ss.length();i++)
{
for(j=1;j<ss.length();j++)
{
if(ss[i]==ss[j]&&i!=j)
{
ss[i]=' ';
}
}
}
for(i=0;i<ss.length();i++)
{
if(ss[i]!=' ')cout<<ss[i]<<" "; /// for unique element print
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n],i,j,k;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
for(j=1;j<n;j++)
{
if(a[i]==a[j]&&i!=j)
{
a[i]=0;
}
}
}
for(i=0;i<n;i++)
{
if(a[i]!=0)cout<<a[i]<<" ";
}
}
Related
I need a string taken as input from the keyboard for example A 2 D F 5 A , it always has 6 total characters, How do I find the last int , in this case 5 and store it in a variable? I cant find anything anywhere.
From the internet I found some code that half works
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
struct not_digit {
bool operator()(const char c) {
return c != ' ' && !std::isdigit(c);
}
};
int main() {
int last;
std::string Serial(" 1 S 4 W 2 A");
not_digit not_a_digit;
std::string::iterator end = std::remove_if(Serial.begin(), Serial.end(), not_a_digit);
std::string all_numbers(Serial.begin(), end);
std::stringstream ss(all_numbers);
std::vector<int> numbers;
for(int i = 0; ss >> i; ) {
numbers.push_back(i);
last = i;
}
cout << last << endl;
return 0;
}
but I dont know how to take "Serial" from keyboard as doing so always results in the last number being 0 for some reason, so instead of 2 i get 0.
This would do:
Reverse the string.
Then find a digit in the string.
Notice the input string may not have digits.
[Demo]
#include <algorithm> // find_if
#include <cctype> // isdigit
#include <fmt/core.h>
#include <ranges>
int main() {
std::string str(" 1 S 4 W 2 A");
auto rev{ str | std::views::reverse };
auto it{ std::ranges::find_if(rev, [](unsigned char c) { return std::isdigit(c); }) };
if (it != std::cend(rev)) {
fmt::print("Last int found: {}\n", *it);
} else {
fmt::print("No int found.\n");
}
}
// Outputs:
//
// Last int found: 2
Also:
Walking the string backwards.
And stopping once you find a digit.
[Demo]
#include <cctype> // isdigit
#include <fmt/core.h>
int main() {
std::string str(" 1 S 4 W 2 A");
auto it{ std::crbegin(str) };
for (; it != crend(str); ++it) {
if (std::isdigit(*it)) {
fmt::print("Last int found: {}\n", *it - '0');
break;
}
}
if (it == crend(str)) {
fmt::print("No int found.\n");
}
}
I want to take an integer and turn it into an array and then store it into a string in C++. But I do not know how to turn an integer into an array and then store it into a string. I am still learning C++, so help me, please. That's how I want it to be done:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int number = 3215;
//store the number into vector
vector<int> numbers;
//vector[0]=3
//vector[1]=2
//vector[2]=1
//vector[5]=5
//and then store it into string
string str;
//like this
//str=3215
return 0;
}
Please help me and show the code as well with explanation
Edit: I have some data to work with integer values with every digit which I can solve my own but for that, I need to first turn the integer into vector and return it as a string. THat's why I want to know how to turn integer into vector first and the that vector into string
Here you are:
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
int n;
std::cin >> n;
std::vector<int> split(static_cast<int>(std::log10(n)) + 1);
auto royal_10 = split.rbegin();
auto cpy{ n };
do {
*royal_10++ = cpy % 10;
} while ((cpy /= 10) != 0);
std::string ret;
ret.reserve(split.size());
std::transform(split.cbegin(), split.cend(), std::back_inserter(ret),
[](int const dig) { return dig + '0'; });
return 0;
}
The easiest is : std::to_string(yourNum);
If you do need the steps:
std::vector<int> res;
int num;
std::cin >> num;
while(num>0)
{
res.insert(res.begin(),num%10);
num/=10;
}
and then
std::stringstream result;
std::copy(res.begin(), res.end(), std::ostream_iterator<int>(result, ""));
Since you insist on placing the integers in a vector first and then converting them to string later (when needed?), this can be a solution:
#include <iostream>
#include <string>
#include <vector>
int main( )
{
std::string number;
std::cin >> number;
std::vector<int> numbers;
numbers.reserve( number.length( ) );
for ( const auto digit : number )
{
numbers.push_back( digit - '0' );
}
std::cout << "\nElements of vector: ";
for ( const auto digit : numbers )
{
std::cout << digit << ' ';
}
std::cout << "\nElements of vector converted to `std::string`: ";
for ( const auto num : numbers )
{
std::string num_str { std::to_string( num ) };
std::cout << num_str << ' ';
}
std::cout << '\n';
}
Sample I/O:
1234
Elements of vector: 1 2 3 4
Elements of vector converted to `std::string`: 1 2 3 4
You are asking for a set of conversion functions, probably something like the code below. The ASCII codes of the digits are in sequential order, therefore transforming a digit character to a digit means subtracting '0' from it.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>
std::vector<int> convert(const std::string& s)
{
std::vector<int> r;
std::transform(s.begin(), s.end(), std::back_inserter(r), [](auto e) {return e - '0'; });
return r;
}
std::string convert(const std::vector<int>& v)
{
std::string r;
std::transform(v.begin(), v.end(), std::back_inserter(r), [](auto e) {return e + '0'; });
return r;
}
std::vector<int> convert(const int n)
{
return convert(std::to_string(n));
}
int main()
{
auto v = convert(3215);
auto s = convert(v);
assert(s == "3215");
}
1)vector in c++ has vector object.push_back(); // which push data(any type) to vector array
2) using an iterator function you can retrieve that data and by dereferencing(*i)
you can receive that data in original form (which you had pushed)
3) use stringstream class or to_string() method to convert into string
//code
`
#include<vector>
#include<iostream>
int main()
{
int number=1234;
string str;
vector <int> obj;
obj.push_back(number);
for(auto i= obj.begin(); i!= obj.end();i++)
{
str = to_string((*i));
cout << end << str;
}
}
`
I have a vector of type struct with some elements, and trying to count the number of occurrences of an element(value) in its corresponding column of the vector. I know how to count on a simple vector, e.g on vector of type string. But am stuck on vector<struct>. Any possible solution or suggestion?
Sample code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
struct my_struct
{
std::string first_name;
std::string last_name;
};
int main()
{
std::vector<my_struct> my_vector(5);
my_vector[0].first_name = "David";
my_vector[0].last_name = "Andriw";
my_vector[1].first_name = "Jhon";
my_vector[1].last_name = "Monta";
my_vector[2].first_name = "Jams";
my_vector[2].last_name = "Ruth";
my_vector[3].first_name = "David";
my_vector[3].last_name = "AAA";
my_vector[4].first_name = "Jhon";
my_vector[4].last_name = "BBB";
for(int i = 0; i < my_vector.size(); i++)
{
int my_count=count(my_vector.begin(), my_vector.end(),my_vector[i].first_name);
/*I need help to count the number of occerencess of each "First_name" in a vector
For example: First_Name:- David COUNT:- 2 ...and so on for each first_names*/
std::cout << "First_Name: " << my_vector[i].first_name << "\tCOUNT: " << my_count << std::endl;
}
return 0;
}
but, the same code for a vector of type string,std::vector<std::string> works properly. see below:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> my_vector;
my_vector.push_back("David");
my_vector.push_back("Jhon");
my_vector.push_back("Jams");
my_vector.push_back("David");
my_vector.push_back("Jhon");
for(int i = 0; i < my_vector.size(); i++)
{
int my_count = count(my_vector.begin(), my_vector.end(),my_vector[i]); //this works good
std::cout << "First_Name: " << my_vector[i] << "\tCOUNT: " << my_count << std::endl;
}
return 0;
}
You have to use std::count_if with correct predicate:
int my_count = std::count_if(my_vector.begin(), my_vector.end(),
[&](const my_struct& s) {
return s.first_name == my_vector[i].first_name;
});
Demo
The functor to replace lambda in C++03:
struct CompareFirstName
{
explicit CompareFirstName(const std::string& s) : first_name(s) {}
bool operator () (const my_struct& person) const
{
return person.first_name == first_name;
}
std::string first_name;
};
and then
int my_count = std::count_if(my_vector.begin(), my_vector.end(),
CompareFirstName(my_vector[i].first_name));
Demo
I would like to know how to find the location of the same words in a vector<string> and push them into a 2d vector.
for example:
for a vector<string> temp{"hello","hey","hey","hi","hello","hi","hey"};
after pushing back the location of the same words into a 2d vector, it will be:
out[0] = 0, 4, //for "hello"
out[1] = 1, 2, 6, //for "hey"
out[2] = 3, 5, //for "hi"
Code example:
...
vector<string> temp{"hello","hey","hey","hi","hello","hi","hey"};
for(int i=0; i<temp.size(); i++){
if (temp.at(i)==temp.at(??))
{????
}
}
out.push_back(???); //push back the location of same words in first row (see example)
...
You could use a map to find previously recorded strings:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
...
vector<string> temp{"hello","hey","hey","hi","hello","hi","hey"};
unordered_map<string, vector<int>> out;
for(int i = 0; i < temp.size(); i++) {
auto& t = temp[i];
auto candidate = out.find(t);
if(candidate == out.end()) {
out[t] = vector<int> { i };
} else {
candidate->second.push_back(i);
}
}
for(auto& o : out) {
cout << o.first << ":";
for(auto& i : o.second) {
cout << " " << i;
}
cout << endl;
}
If you need to use vectors, this is will give your required output using find_if and C++ 11
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <string>
using pair_element = std::pair<std::string, std::vector<int> >;
using pair_vector = std::vector<pair_element>;
pair_vector countWords(std::vector<std::string> wordVec)
{
pair_vector pairList;
for(int i=0; i < wordVec.size(); i++)
{
std::string word = wordVec[i];
auto it = std::find_if( pairList.begin(), pairList.end(),
[word](const pair_element& element){ return element.first == word;} );
//Item exists
if( it != pairList.end())
{
//increment count
it->second.push_back(i);
}
//Item does not exist
else
{
//Not found, insert
pairList.push_back( pair_element(wordVec[i], {i}) );
}
}
return pairList;
}
int main()
{
std::vector<std::string> temp{"hello","hey","hey","hi","hello","hi","hey"};
auto wordCount = countWords(temp);
int count = 0;
for(auto kv : wordCount)
{
std::cout << "out[" << count << "] : ";
for(int c : kv.second)
std::cout << c << ' ';
std::cout << std::endl;
count++;
}
}
how can I store the values returned from a function to a string as comma seperated values. Can anyone help me..?
const myVector &vecList = obj.get_List();
vector<myNumVector *>::const_iterator iter;
for (iter= vecList.begin(); iter!= vecList.end(); iter++)
{
string myNum = (*iter)->get_myNum();
string myNumList = ?
//myNumList should be = drt123,ret34,dfghgd234.... if these are the return values
} //can we achive this by use of some sting functions..?
As can be seen from the links I posted, there are lots of ways to do this. Here is, I believe, the simplest:
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <boost/assign/list_of.hpp>
using boost::assign::list_of;
namespace ba = boost::assign;
vector<string> victor = list_of
("Clarence Oveur")
("Roger Murdock")
("Victor Basta");
int main() {
string result;
for(vector<string>::iterator it = victor.begin();
it != victor.end();
++it) {
if(it != victor.begin()) {
result += ", ";
}
result += *it;
}
cout << result << "\n";
}
EDIT: To translate directly to OP's question:
const myVector &vecList = obj.get_List();
vector<myNumVector *>::const_iterator iter;
string myNumlist;
for (iter= vecList.begin(); iter!= vecList.end(); iter++)
{
string myNum = (*iter)->get_myNum();
if(iter!=vecList.begin()) {
nyNumList += ",";
}
myNumList += myNum;
}
EDIT: Simplified by removing bool first from previous solution.
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
int main () {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
std::stringstream list;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(list, ","));
std::cout << list.str();
return 0;
}
Outputs: 1,2,3,4,
more modern approach, also solving the trailing ","
#include <string>
#include <numeric>
#include <iostream>
int main() {
const auto v = {1, 2, 3, 4};
const auto list = std::accumulate(begin(v), end(v), std::string{}, [](const std::string& so_far, const auto& next) {
return so_far + (so_far.empty() ? "" : ", ") + std::to_string(next);
});
std::cout << list;
return 0;
}
Yes, this can be achieved using string functions, along with a handful other methods.
Given a string myNumList defined outside the loop, you could simply
myNumList += "," + myNum;
although that would add an extraneous comma in the beinning, so check if iter is pointing there first:
if(iter != vecList.begin())
myNumList += ',';
myNumList += myNum;