How to make a 2d vector from input string? - c++

I got this problem in one of the coding questions in my university exam where I knew the answer but couldn't follow as I didn't know how to parse the string and convert it into a 2d vector.
So I have got a 2d vector in the form of a string
"[[1,4], [5,7], [4,1], [8,9]]"
I want to convert this string into a vector<vector<int>>
EDIT
Maybe I wasn't clear the last time and there's one thing I missed. The string is
"[[1,4], [5,7], [4,1], [8,9]]"
I want this string to be in the form of a 2d vector. So, let's say I have a vector vec defined as vector<vector<int>> vec. Then vec[0]={1,4}, vec[1]={5,7}, vec[2]={4,1}, vec[3]={8,9}. Below is what I did and it shows incorrect output
#include<iostream>
#include<sstream>
#include<vector>
using namespace std;
int main()
{
string str="[[1,4], [5,7], [4,1], [8,9]]";
stringstream ss(str);
vector<vector<int>> vec;
string temp;
while(ss>>temp){
cout<<temp<<endl;
vector<int> t;
int x,y;
stringstream ss2(temp);
while(ss2>>x>>y)
{
t.push_back(x);
t.push_back(y);
}
vec.push_back(t);
}
}

The generic answer is to write a recursive descent parser (look it up). It's a fancy way of saying that you write a function for each of the non-terminals (vector2, vector, int) then you usually look at just the first byte to figure out to do. In this case your grammar might be:
vector2 = "[" vector (, " " vector) "]"
vector = "[" int (, number) "]"
number = 0 | 1 [0-9]
Then you implement number, vector and vector_vector similar to how #StPiere showed you previously.
I usually use c, and I found this generic function signature to be a useful start:
char *parse_something(const char *s, something *v)
where s is the string you are parsing and the return value is what the next thing is you want to parse.

Here is quick implementation Godbolt:
Note: This answer does not handle cases where integers have more than one digit. It is not generic or easily extensible, but as this is a homework question, you can understand and improve the code.
#include <string>
#include <vector>
#include <istream>
#include <sstream>
#include <cctype>
#include <iostream>
#include <iterator>
int main()
{
std::string input{"[[1,4], [5,7], [4,1], [8,9]]"};
std::stringstream ss{input};
auto it = std::istream_iterator<char>{ss};
std::vector<std::vector<int>> output;
std::vector<int> inner;
// Loop through the string, one character at a time
while (it != std::istream_iterator<char>{})
{
++it;
// If we encounter a digit, push it into the inner vector
if (std::isdigit(*it))
{
// Dirty hack to convert char to integer (assumes ASCII)
inner.push_back(*it - 48);
}
// If you encounter a ']' char, then push inner vector into the outer vector
// and then clear the inner vector
// For the final ']', the inner vector will be size 0, ignore this case
if (*it == ']')
{
if (inner.size() != 0)
{
output.push_back(inner);
}
inner.clear();
}
}
}

#include <iostream>
#include <vector>
using namespace std;
template <typename Range>
void print_range(const Range& r)
{
for (const auto& e : r)
cout << e << " ";
cout << endl;
}
int main()
{
vector<int> v;
vector<vector<int>> vv;
char c;
int cnt = 0;
while (cin >> c)
{
if (c == ',' || c == ' ' || c == '\n')
{
continue;
}
if (c == '[')
{
++cnt;
v.clear();
continue;
}
if (c == ']')
{
--cnt;
if (cnt == 0)
break;
vv.push_back(v);
v.clear();
continue;
}
cin.unget();
int x;
if (cin >> x)
v.push_back(x);
}
for (const auto& vec : vv)
print_range(vec);
}

Related

How to convert an input string into an array in C++? [duplicate]

This question already has answers here:
C++ function split string into words
(1 answer)
taking input of a string word by word
(3 answers)
Right way to split an std::string into a vector<string>
(12 answers)
Closed last year.
myStr = input("Enter something - ")
// say I enter "Hi there"
arrayStr = myStr.split()
print(arrayStr)
// Output: ['Hi', 'there']
What is the exact C++ equivalent of this code? (My aim is to further iterate over the array and perform comparisons with other arrays).
One way of doing this would be using std::vector and std::istringstream as shown below:
#include <iostream>
#include <string>
#include<sstream>
#include <vector>
int main()
{
std::string input, temp;
//take input from user
std::getline(std::cin, input);
//create a vector that will hold the individual words
std::vector<std::string> vectorOfString;
std::istringstream ss(input);
//go word by word
while(ss >> temp)
{
vectorOfString.emplace_back(temp);
}
//iterate over all elements of the vector and print them out
for(const std::string& element: vectorOfString)
{
std::cout<<element<<std::endl;
}
return 0;
}
You can use string_views to avoid generating copies of the input string (efficient in memory), it literally will give you views on the words in the string, like this :
#include <iostream>
#include <string_view>
#include <vector>
inline bool is_delimiter(const char c)
{
// order by frequency in your input for optimal performance
return (c == ' ') || (c == ',') || (c == '.') || (c == '\n') || (c == '!') || (c == '?');
}
auto split_view(const char* line)
{
const char* word_start_pos = line;
const char* p = line;
std::size_t letter_count{ 0 };
std::vector<std::string_view> words;
// while parsing hasn't seen the terminating 0
while(*p != '\0')
{
// if it is a character from a word then start counting the letters in the word
if (!is_delimiter(*p))
{
letter_count++;
}
else
{
//delimiter reached and word detected
if (letter_count > 0)
{
//add another string view to the characters in the input string
// this will call the constructor of string_view with arguments const char* and size
words.emplace_back(word_start_pos, letter_count);
// skip to the next word
word_start_pos += letter_count;
}
// skip delimiters for as long as you encounter them
word_start_pos++;
letter_count = 0ul;
}
// move on to the next character
++p;
}
return words;
}
int main()
{
auto words = split_view("the quick brown fox is fast. And the lazy dog is asleep!");
for (const auto& word : words)
{
std::cout << word << "\n";
}
return 0;
}
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
template <typename Out>
void split(const std::string &s, char delim, Out result) {
std::istringstream iss(s);
std::string item;
while (std::getline(iss, item, delim)) {
*result++ = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
std::vector<std::string> x = split("one:two::three", ':');
Where 'x' is your converted array with 4 elements.
Basically #AnoopRana's solution but using STL algorithms and removing punctuation signs from words:
[Demo]
#include <cctype> // ispunct
#include <algorithm> // copy, transform
#include <iostream> // cout
#include <iterator> // istream_iterator, ostream_iterator
#include <sstream> // istringstream
#include <string>
#include <vector>
int main() {
const std::string s{"In the beginning, there was simply the event and its consequences."};
std::vector<std::string> ws{};
std::istringstream iss{s};
std::transform(std::istream_iterator<std::string>{iss}, {},
std::back_inserter(ws), [](std::string w) {
w.erase(std::remove_if(std::begin(w), std::end(w),
[](unsigned char c) { return std::ispunct(c); }),
std::end(w));
return w;
});
std::copy(std::cbegin(ws), std::cend(ws), std::ostream_iterator<std::string>{std::cout, "\n"});
}
// Outputs:
//
// In
// the
// beginning
// there
// was
// simply
// the
// event
// and
// its
// consequences

How do I print the frequency of each word in the given input string using two vectors?

Here is my approach where I have tried to split the string into words and then move forward but this is not working.
For instance, the input is: hey hi Mark hi mark
Then the output should be:
hey-1
hi-2
Mark-1
hi-2
mark-1
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<vector<string> > strs;
string str;
cout<<"Enter your strings"<<endl;
getline(cin, str);
int len=str.length();
int j=0;
string s="";
for(int i=0; i<len; i++){
s+=str[i];
if(str[i+1]==' ' || i+1==len){
strs[0][j]=s;
s="";
j++;
i++;
}
}
strs[0][j]="NULL";
int freq;
vector<int> frequency;
for(int n=0; strs[0][n]!="NULL" ;n++){
freq=1;
for(int m=0; strs[0][m]!="NULL"; m++){
if(strs[0][n]==strs[0][m]){
freq++;
}
frequency.push_back(freq);
}
}
for(int x=0; strs[0][x]!="NULL"; x++){
cout<<strs[0][x]<<" - "<<frequency[x]<<endl;
}
return 0;
}
In your code, you have tried to access string elements via its index, which sometimes raises segmentation fault. To solve your problem, I came up with below mention solution.
#include <iostream>
#include <string>
#include <map>
/* getWordFrequency : function with return type std::map<std::string, int>
Param1: Input string
Param2: Default delimiter as " "(void space).
*/
std::map<std::string, int> getWordFrequency(const char *input_string, char c = ' ')
{
// Container to store output result
std::map<std::string, int> result;
// Iteration loop
do{
// Iteration pointer to iterate Character by Character
const char *begin = input_string;
// Continue loop until delimeter or pointer to self detects
while(*input_string != c && *input_string){
// Jump to next character
input_string++;
}
// Iterator for output result container
std::map<std::string, int>::iterator finder = result.find(std::string(begin, input_string));
// Find element using iterator
if(finder != result.end()){
// Element already present in resultunt map then increment frequency by one
finder->second += 1;
} else {
// If no element found then insert new word with frequency 1
result.insert(std::pair<std::string, int>(std::string(begin, input_string),1));
}
} while (0 != *input_string++); // Continue till end of string
return result;
}
int main()
{
// Your string
std::string input_string = "hey hi Mark hi mark";
// Container to catch result
std::map<std::string, int> frequency = getWordFrequency(input_string.c_str());
// Printing frequency of each word present in string
for (auto element : frequency){
std::cout << element.first << "-" << element.second << std::endl;
}
return 0;
}
So, I think your approach using 2 std::vectors is unfortunately wrong. You do not fully understand the difference between char and std::string.
You need to learn abaout that.
There is a more or less standard approach for counting something in a container, like a string or in general.
We can use an associative container like a std::map or a std::unordered_map. And here we associate a "key", in this case the "word" to count, with a value, in this case the count of the specific word.
And luckily the maps have a very nice index operator[]. This will look for the given key and, if found, return a reference to the value. If not found, then it will create a new entry with the key and return a reference to the new entry. So, in both cases, we will get a reference to the value used for counting. And then we can simply write:
std::map<std::string, int> counter{};
counter[word]++;
And that's it. More is not necessary. Please see:
#include <iostream>
#include <string>
#include <sstream>
#include <unordered_map>
int main() {
// Our test String
std::string text{"hey hi Mark hi mark"};
// Here, we will store the result of the counting
std::unordered_map<std::string, unsigned int> counter;
// Now count all words. This one line does all the counting
for (std::istringstream iss{text}; iss >> text; counter[text]++);
// Show result to user
for (const auto& [word, count] : counter) std::cout << word << '-' << count << ' ';
}
It seems also that splitting a string is some how difficult for you. Also here are many many ppossible solutions available.
One of the more sophisticated and more advanced solution is to use the std::sregex_token_iterator. With that you can easily iterate over patterns (described by a std::regex) in a string.
The final code will look nearly the same, but the result will be better, since for example punctuation can be excluded.
Example:
#include <iostream>
#include <string>
#include <unordered_map>
#include <regex>
#include <iterator>
using Iter = std::sregex_token_iterator;
const std::regex re{R"(\w+)"};
int main() {
// Our test String
std::string text{"hey hi Mark, hi mark."};
// Here, we will store the result of the counting
std::unordered_map<std::string, unsigned int> counter;
// Now count all words. This one line does all the counting
for (Iter word(text.begin(), text.end(), re); word != Iter(); counter[*word++]++);
// Show result to user
for (const auto& [word, count] : counter) std::cout << word << '-' << count << ' ';
}

Is there way to reduce memory consumption in my c++ code?

I am new in c++ and I am trying to solve educational exercise in quiz platform, but in this platform I should use no more than 64 MB of memory. My code use more than 130 MB.
#include <sstream>
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <map>
using namespace std;
template<class Container>
void splitString(const std::string &basicString, Container &cont, char delim = ' ') {
std::stringstream ss(basicString);
std::string token;
while (std::getline(ss, token, delim)) {
cont.push_back(token);
}
}
int main() {
int target = 0;
int count = 0;
std::map<int, int> set;
string line;
ifstream fileR("input.txt");
std::vector<string> c;
if (fileR.is_open()) {
while (getline(fileR, line)) {
if (count == 0) {
target = std::stoi(line);
count++;
continue;
}
splitString(line, c);
for (auto &d : c) {
int key = std::stoi(d);
if (set.count(key)) {
set[key] += 1;
} else {
set[key] = 1;
}
}
c.clear();
}
fileR.clear();
fileR.close();
}
ofstream fileW;
fileW.open("output.txt");
bool found = false;
for (const auto &p : set) {
int d = target - p.first;
if (set.count(d)) {
if (p.first != d || set[d] > 1) {
fileW << 1;
found = true;
break;
}
}
}
if (!found) {
fileW << 0;
}
fileW.close();
return 0;
}
What I can add, remove or change for keep within the coveted 64 MB? I tried free memory manually but no effects. I am not sure that is possible to write more effective algorithm.
Your vector (c) is declared outside the loop and is not cleared every time you call split string. This means every time you pass in a string to split, your vector contains stuff from the previous run. Is this intentional? If it is not, then move your vector into the loop, before you call split string, or clear it in your split string function. If it is intentional please provide more info about what your code is supposed to do.

string repetition replaced by hyphen c++

I am a beginner at coding, and was trying this question that replaces all repetitions of a letter in a string with a hyphen: i.e ABCDAKEA will become ABCD-KE-.I used the switch loop and it works, but i want to make it shorter and maybe use recursion to make it more effective. Any ideas?
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char x[100];
int count[26]={0}; //initialised to zero
cout<<"Enter string: ";
cin>>x;
for(int i=0; i<strlen(x); i++)
{
switch(x[i])
{
case 'a':
{
if((count[0]++)>1)
x[i]='-';
}
case 'b':
{
if((count[1]++)>1)
x[i]='-';
}
case 'c':
{
if((count[2]++)>1)
x[i]='-';
}
//....and so on for all alphabets, ik not the cutest//
}
}
Iterate through the array skipping whitespace, and put characters you've never encountered before in std::set, if you find them again you put them in a duplicates std::set if you'd like to keep track of how many duplicates there are, otherwise change the value of the original string at that location to a hyphen.
#include <iostream>
#include <string>
#include <cctype>
#include <set>
int main() {
std::string s("Hello world");
std::set<char> characters;
std::set<char> duplicates;
for (std::string::size_type pos = 0; pos < s.size(); pos++) {
char c = s[pos];
// std::isspace() accepts an int, so cast c to an int
if (!std::isspace(static_cast<int>(c))) {
if (characters.count(c) == 0) {
characters.insert(c);
} else {
duplicates.insert(c);
s[pos] = '-';
}
}
}
return 0;
}
Naive (inefficient) but simple approach, requires at least C++11.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
std::string f(std::string s)
{
auto first{s.begin()};
const auto last{s.end()};
while (first != last)
{
auto next{first + 1};
if (std::isalpha(static_cast<unsigned char>(*first)))
std::replace(next, last, *first, '-');
first = next;
}
return s;
}
int main()
{
const std::string input{"ABCDBEFKAJHLB"};
std::cout << f(input) << '\n';
return 0;
}
First, notice English capital letters in ASCII table fall in this range 65-90. Casting a capital letter static_cast<int>('A') will yield an integer. If after casing the number is between 65-90, we know it is a capital letter. For small letters, the range is 97-122. Otherwise the character is not a letter basically.
Check create an array or a vector of bool and track the repetitive letters. Simple approach is
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str("ABCDAKEAK");
vector<bool> vec(26,false);
for(int i(0); i < str.size(); ++i){
if( !vec[static_cast<int>(str[i]) - 65] ){
cout << str[i];
vec[static_cast<int>(str[i]) - 65] = true;
}else{
cout << "-";
}
}
cout << endl;
return 0;
}
Note: I assume the input solely letters and they are capital. The idea is centered around tracking via bool.
When you assume input charactor encode is UTF-8, you can refactor like below:
#include <iostream>
#include <string>
#include <optional>
#include <utility>
std::optional<std::size_t> char_to_index(char u8char){
if (u8'a' <= u8char && u8char <= u8'z'){
return u8char - u8'a';
}
else if (u8'A' <= u8char && u8char <= u8'A'){
return u8char - u8'A';
}
else {
return std::nullopt;
}
}
std::string repalce_mutiple_occurence(std::string u8input, char u8char)
{
bool already_found[26] = {};
for(char& c : u8input){
if (const auto index = char_to_index(c); index && std::exchange(already_found[*index], true)){
c = u8char;
}
}
return u8input;
}
int main(){
std::string input;
std::getline(std::cin, input);
std::cout << repalce_mutiple_occurence(input, u8'-');
}
https://wandbox.org/permlink/UnVJHWH9UwlgT7KB
note: On C++20, you should use char8_t instead of using char.

How to remove consonants from a string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Here is my code:
#include <iostream>
#include <string>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--)
{
string str;
char a[] = {'a','e','i','o','u','A','E','I','O','U'};
getline(cin, str);
for(int i=0 ;i<str.length(); i++)
{
for(int j=0; j<10; j++)
{
if(str[i]==a[j])
{
cout << str[i];
}
}
}
cout << "\n";
}
return 0;
}
Test cases are :
HmlMqPhBfaVokhR
wdTSFuI
IvfHOSNv
I am not removing anything but I am printing only vowels. But, some test cases didn't pass. Maybe this code doesn't work on multiple test cases.
Try this for proper console in :
int main()
{
int n;
std::cin >> n;
std::cin.ignore(); // fix
/* remaining code */
return 0;
}
> To find the vowels in a string
On way of finding the vowels in a string is using a std::binary_search each character of the given string in a vowel table.
Make a sorted array of char s of all vowels(i.e. vowels array).
For each char of the input string, std::binary_search in the
vowels array.
If std::binary_search returns true(meaning the char is an vowel), print the char of the string.
Following is the example code! (See live online)
#include <iostream>
#include <string>
#include <algorithm> // std::for_each, std::binary_search, std::sort
#include <array> // std::array
int main()
{
std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
std::sort(a.begin(), a.end()); // need sorted array for std::binary_search
const std::string str{ "HmlMqPhBfaVokhR wdTSFuI IvfHOSNv" };
std::for_each(str.cbegin(), str.cend(), [&](const char str_char)
{
if (std::binary_search(a.cbegin(), a.cend(), str_char))
std::cout << str_char << " ";
});
return 0;
}
Output:
a o u I I O
> To remove the vowels from a string
Use erase-remove idiom as follows(till c++17†).
Make a sorted array of char s of all vowels(i.e. vowels array).
Using std::remove_if, collect the iterators pointing to the characters, which are vowels. A lambda function can be used as the predicate for std::remove_if, where the std::binary_search is used to check the char in the string exists in the vowels array.
Using std::string::erase, erase all the collected characters(i.e. vowels) from the string.
Following is an example code! (See live online)
#include <iostream>
#include <string>
#include <algorithm> // std::sort, std::binary_search, std::remove_if
#include <array> // std::array
int main()
{
std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
std::sort(a.begin(), a.end()); // need sorted array for std::binary_search
std::string str{ "Hello World" };
// lambda(predicate) to check the `char` in the string exist in vowels array
const auto predicate = [&a](const char str_char) -> bool {
return std::binary_search(a.cbegin(), a.cend(), str_char);
};
// collect the vowels
const auto vowelsToRemove = std::remove_if(str.begin(), str.end(), predicate);
// erase the collected vowels using std::string::erase
str.erase(vowelsToRemove, str.end());
std::cout << str << "\n";
return 0;
}
Output:
Hll Wrld
† Since c++20, one can use std::erase_if for this, which would be less error prone than the the above one. (See online live using GCC 9.2)
#include <iostream>
#include <string> // std::string, std::erase_if
#include <array> // std::array
int main()
{
std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
std::sort(a.begin(), a.end()); // need sorted array for std::binary_search
std::string str{ "Hello World" };
// lambda(predicate) to check the `char` in the string exist in vowels array
const auto predicate = [&a](const char str_char) -> bool {
return std::binary_search(a.cbegin(), a.cend(), str_char);
};
std::erase_if(str, predicate); // simply erase
std::cout << str << "\n";
return 0;
}
> To remove the consonants from a string
To remove the consonants from the given string, in the above predicate negate the result of std::binary_search. (See live online)
const auto predicate = [&a](const char str_char) -> bool {
return !std::binary_search(a.cbegin(), a.cend(), str_char);
// ^^ --> negate the return
};
As side notes,
Avoid the #include<bits/stdc++.h> Read more: Why should I not #include <bits/stdc++.h>?
Do not practice with using namespace std; Read more: Why is "using namespace std;" considered bad practice?
Apart from the std::getline problem already answered:
for(int i=0 ;i<str.length(); i++)
{
for(int j=0; j<10; j++)
{
if(str[i] == a[j])
{
// this is the one you do NOT want to print...
// cout<<str[i];
// skip instead:
goto SKIP;
}
}
std::cout << str[i]; // output the one NOT skipped...
SKIP: (void)0;
}
OK, don't want to start any discussion about usage of goto, there are many ways to avoid it, e. g. by packing the inner for loop into a separate (inline) function. You can have it easier, though, as there already exists such a function; code gets even easier with a range-based for loop:
for(auto c : str)
{
if(!strchr("aeiouAEIOU", c))
{
std::cout << c;
}
}
strchr (from cstring) returns a pointer to the first character in the string equal to the reference character - or nullptr if not found...
To really remove the vowels from the string in a modern C++ way, consider this:
str.erase(std::remove_if(
str.begin(), str.end(),
[](char c) { return strchr("aeiouAEIOU", c) != nullptr; }
), str.end());
Your code probably should looks like (please see comments inline):
#include <iostream>
#include <string>
using namespace std;
int main() {
string vowels = "aeiouAEIOU";
int n;
cin>>n; // assume this stands for line count
while(n-- >= 0)
{
string str, result;
getline(cin, str);
for(int i=0 ;i<str.length(); i++)
{
if (vowels.find(str[i]) != std::string::npos)
result += str[i]; // add character to result if it is not consonant
}
cout<<result<<"\n"; // print result
}
return 0;
}