How can I check if string value exists in array of chars? - c++

#include <iostream>
using namespace std;
int main()
{
string str = "cab";
string d = "";
char s[] = {'a', 'b', 'c', 'd', 'e'};
for(int i = 0; i < sizeof(s) / sizeof(s[0]); i++){
for(int j = 0; j < str.length(); j++){
if(str[j] == s[i]){
d += s[i];
}
}
}
cout << d << endl;
return 0;
}
I wanna check if the string "cab" for example exists in array of chars like in my case, it should exist, no matter of position in the element in the array of chars.

Assuming that your sub string will not have duplicates, you could use an unordered_set. So you essentially iterate over your s[] and for each character, you will check if the set contains that particular character.
The unordered_set allows O(1) searching, so your algorithm should run in O(n) (n = size of s).
When you find a character in the set which is also within the array, you remove it and continue traversing the array. If by the time your are done traversing the array the set is empty, then you know that your array contains that substring. You can also check to see that the set is not empty each time you remove a character from it, this should reduce execution time.

Not my code:
#include <string>
#include <iostream>
#include <algorithm>
void print(std::string::size_type n, std::string const &s)
{
if (n == std::string::npos) {
std::cout << "not found\n";
} else {
std::cout << "found: " << s.substr(n) << '\n';
}
}
int main()
{
std::string str = "cab";
std::string::size_type n;
std::string const s = "This is a string";
// search from beginning of string
n = s.find("is");
print(n, s);
// search from position 5
n = s.find("is", 5);
print(n, s);
// find a single character
n = s.find('a');
print(n, s);
// find a single character
n = s.find('q');
print(n, s);
//not the best way
for(char c : s)
s.find(c); //will be npos if it doesn't exist
//better
std::includes( s.begin(), s.end(),
str.begin(), str.end() );
}

Related

Replace every letter with its position in the alphabet for a given string

The first step, I changed the string to a lowercase, after that I removed all the non letters from the string, now I am struggling to replace each letter with the alphabet position.
does anyone know how to do such a thing?
Thank you!
string alphabet_position(string message){
string alphabet= "abcdefghijklmnopqrstuvwxyz";
int aplha_numbers[100];
for_each(message.begin(), message.end(), [](char & c){
c = ::tolower(c);
});
for(int i=0; i< message.size(); i++){
if(message[i] < 'a' || message[i] > 'z'){
message.erase(i, 1);
i--;
}
}
for(int j=0; j<message.size(); j++){
int index = alphabet.find(message[j]);
aplha_numbers[j]= index +1;
}
std::ostringstream os;
for(int z: aplha_numbers){
os<<z;
}
std::string str(os.str());
return str;
}
Now I have a different issue , I am getting the alphabet positions but I also get a lot of garbage values after the last letter.
As an example Input: abc
output 123 and after that a lot of numbers 32761004966.....
There are a few issues in your code:
Your main bug was that in this line:
for (int z : aplha_numbers)
You go over all the 100 elements in the allocated array, not just the valid entries.
In my solution there's no need for such an array at all. The stringstream objec is updated directly.
The position of a lower case character c is simply c-'a'+1. No need for a lookup table (at least assuming ascii input).
There's no need to actually change the input string by making it a lower case. This can be done on the fly as you traverse it.
Here's a complete fixed version:
#include <string>
#include <sstream>
#include <iostream>
#include <cctype>
std::string alphabet_position(std::string message)
{
std::ostringstream os;
for (auto const & c : message)
{
char c_lower = std::tolower(c);
if (c_lower < 'a' || c_lower > 'z') continue;
int pos = c_lower - 'a' + 1;
os << pos;
}
return os.str();
}
int main()
{
std::string s_in = "AbC";
std::string s_out = alphabet_position(s_in);
std::cout << "in:" << s_in << ", out:" << s_out << std::endl;
return 0;
}
Output:
in:AbC, out:123
A side note: it's better to avoid using namespace std;. See here: Why is "using namespace std;" considered bad practice?

Removing all the vowels in a string in c++

I've written a code that removes all vowels from a string in c++ but for some reason it doesn't remove the vowel 'o' for one particular input which is: zjuotps.
Here's the code:
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
cin >> s;
string a = "aeiouyAEIOUY";
for (int i = 0; i < s.length(); i++){
for(int j = 0; j < a.length(); j++){
if(s[i] == a[j]){
s.erase(s.begin() + i);
}
}
}
cout << s;
return 0;
}
When I input: zjuotps
The Output I get is: zjotps
This is a cleaner approach using the C++ standard library:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string input = "zjuotps";
std::string vowels = "aeiouyAEIOUY";
auto predicate = [&vowels](char c) { return vowels.find(c) != std::string::npos; };
auto iterator = std::remove_if(input.begin(), input.end(), predicate);
input.erase(iterator, input.end());
cout << input << endl;
}
Edit:
as #RemyLebeau pointed out, std::erase_if can be used which is introduced in c++20 and the answer becomes one line of code:
std::erase_if(input, [&vowels](char c) { return vowels.find(c) != std::string::npos; });
You can develop a solution by adding the matching characters to the new string object. The eliminate() method writes the character to the result object if the characters in the input object doesn't match the characters in the remove object.
#include <iostream>
/**
* #brief This method scans the characters in the "input" object and writes
* the characters not in the "remove" object to the "result" object.
* #param input This object contains the characters to be scanned.
* #param remove This object contains characters that will not match.
* #param result Non-match result data is writed to this object.
*/
void eliminate(std::string input, std::string remove, std::string &result);
int main()
{
std::string input = "zjuotpsUK", remove = "aeiouyAEIOUY", result;
eliminate(input, remove, result);
std::cout << result << std::endl;
return 0;
}
void eliminate(std::string input, std::string remove, std::string &result)
{
for (size_t i = 0, j = 0; i < input.length(); i++)
{
for(j = 0; j < remove.length(); j++)
if(input[i] == remove[j])
break;
if(j == remove.length())
result += input[i];
}
}
In your code here, I replaced s with input_str, and a with vowels, for readability:
for (int i = 0; i < input_str.length(); i++){
for(int j = 0; j < vowels.length(); j++){
if(input_str[i] == vowels[j]){
input_str.erase(input_str.begin() + i);
}
}
}
The problem with your current code above is that each time you erase a char in the input string, you should break out of the vowels j loop and start over again in the input string at the same i location, checking all vowels in the j loop again. This is because erasing a char left-shifts all chars which are located to the right, meaning that the same i location would now contain a new char to check since it just left-shifted into that position from one position to the right. Erroneously allowing i to increment means you skip that new char to check in that same i position, thereby leaving the 2nd vowel in the string if 2 vowels are in a row, for instance. Here is the fix to your immediate code from the question:
int i = 0;
while (i < s.length()){
bool char_is_a_vowel = false;
for(int j = 0; j < a.length(); j++){
if(s[i] == a[j]){
char_is_a_vowel = true;
break; // exit j loop
}
}
if (char_is_a_vowel){
s.erase(s.begin() + i);
continue; // Do NOT increment i below! Skip that.
}
i++;
}
However, there are many other, better ways to do this. I'll present some below. I personally find this most-upvoted code difficult to read, however. It requires extra study and looking up stuff to do something so simple. So, I'll show some alternative approaches to that answer.
Approach 1 of many: copy non-vowel chars to new string:
So, here is an alternative, simple, more-readable approach where you simply scan through all chars in the input string, check to see if the char is in the vowels string, and if it is not, you copy it to an output string since it is not a vowel:
Just the algorithm:
std::string output_str;
for (const char c : input_str) {
if (vowels.find(c) == std::string::npos) {
output_str.push_back(c);
}
}
Full, runnable example:
#include <iostream> // For `std::cin`, `std::cout`, `std::endl`, etc.
#include <string>
int main()
{
std::string input_str = "zjuotps";
std::string vowels = "aeiouyAEIOUY";
std::string output_str;
for (const char c : input_str)
{
if (vowels.find(c) == std::string::npos)
{
// char `c` is NOT in the `vowels` string, so append it to the
// output string
output_str.push_back(c);
}
}
std::cout << "input_str = " << input_str << std::endl;
std::cout << "output_str = " << output_str << std::endl;
}
Output:
input_str = zjuotps
output_str = zjtps
Approach 2 of many: remove vowel chars in input string:
Alternatively, you could remove the vowel chars in-place as you originally tried to do. But, you must NOT increment the index, i, for the input string if the char is erased since erasing the vowel char left-shifs the remaining chars in the string, meaning that we need to check the same index location again the next iteration in order to read the next char. See the note in the comments below.
Just the algorithm:
size_t i = 0;
while (i < input_str.length()) {
char c = input_str[i];
if (vowels.find(c) != std::string::npos) {
input_str.erase(input_str.begin() + i);
continue;
}
i++;
}
Full, runnable example:
#include <iostream> // For `std::cin`, `std::cout`, `std::endl`, etc.
#include <string>
int main()
{
std::string input_str = "zjuotps";
std::string vowels = "aeiouyAEIOUY";
std::cout << "BEFORE: input_str = " << input_str << std::endl;
size_t i = 0;
while (i < input_str.length())
{
char c = input_str[i];
if (vowels.find(c) != std::string::npos)
{
// char `c` IS in the `vowels` string, so remove it from the
// `input_str`
input_str.erase(input_str.begin() + i);
// do NOT increment `i` here since erasing the vowel char above just
// left-shifted the remaining chars in the string, meaning that we
// need to check the *same* index location again the next
// iteration!
continue;
}
i++;
}
std::cout << "AFTER: input_str = " << input_str << std::endl;
}
Output:
BEFORE: input_str = zjuotps
AFTER: input_str = zjtps
Approach 3 of many: high-speed C-style arrays: modify input string in-place
I borrowed this approach from "Approach 1" of my previous answer here: Removing elements from array in C
If you are ever in a situation where you need high-speed, I'd bet this is probably one of the fastest approaches. It uses C-style strings (char arrays). It scans through the input string, detecting any vowels. If it sees a char that is NOT a vowel, it copies it into the far left of the input string, thereby modifying the string in-place, filtering out all vowels. When done, it null-terminates the input string in the new location. In case you need a C++ std::string type in the end, I create one from the C-string when done.
Just the algorithm:
size_t i_write = 0;
for (size_t i_read = 0; i_read < ARRAY_LEN(input_str); i_read++) {
bool char_is_a_vowel = false;
for (size_t j = 0; j < ARRAY_LEN(input_str); j++) {
if (input_str[i_read] == vowels[j]) {
char_is_a_vowel = true;
break;
}
}
if (!char_is_a_vowel) {
input_str[i_write] = input_str[i_read];
i_write++;
}
}
input_str[i_write] = '\n';
Full, runnable example:
#include <iostream> // For `std::cin`, `std::cout`, `std::endl`, etc.
#include <string>
/// Get the number of elements in an array
#define ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))
int main()
{
char input_str[] = "zjuotps";
char vowels[] = "aeiouyAEIOUY";
std::cout << "BEFORE: input_str = " << input_str << std::endl;
// Iterate over all chars in the input string
size_t i_write = 0;
for (size_t i_read = 0; i_read < ARRAY_LEN(input_str); i_read++)
{
// Iterate over all chars in the vowels string. Only retain in the input
// string (copying chars into the left side of the input string) all
// chars which are NOT vowels!
bool char_is_a_vowel = false;
for (size_t j = 0; j < ARRAY_LEN(input_str); j++)
{
if (input_str[i_read] == vowels[j])
{
char_is_a_vowel = true;
break;
}
}
if (!char_is_a_vowel)
{
input_str[i_write] = input_str[i_read];
i_write++;
}
}
// null-terminate the input string at its new end location; the number of
// chars in it (its new length) is now equal to `i_write`!
input_str[i_write] = '\n';
std::cout << "AFTER: input_str = " << input_str << std::endl;
// Just in case you need it back in this form now:
std::string str(input_str);
std::cout << " C++ str = " << str << std::endl;
}
Output:
BEFORE: input_str = zjuotps
AFTER: input_str = zjtps
C++ str = zjtps
See also:
[a similar answer of mine in C] Removing elements from array in C

How to iterate through every letter in a vector of strings?

As mentioned in the title, how do I iterate through every letter in a vector of strings?
If someone types in some words like
hello
random
stack
and then enters a letter like e
I want to print out which words contains the letter "e" which is "hello". So how do I check every character in the vector for that character and then print the word(s) out?
for (int i {}; i < gift_bag.gifts.size(); ++i)
{
if (gift_bag.gifts[i] == letter)
{
cout << gift_bag.gifts[i] << endl;
}
}
This is what I've done but it is wrong because it check if a string is equal a character. I want to iterate through the letters in each word.
gift_bag is defined as Gift_Bag_Type which is a struct containing a vector<string> named gifts. And letter is char
The ranged for loop and find function in std::string will help you.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> vec = { "hello", "random", "stack" };
constexpr char letter = 'e';
for (const auto &str : vec)
if (str.find(letter) != std::string::npos)
std::cout << str << '\n'; // hello
}
You'll need two loops, one to iterate through the vector, then a nested loop to iterate through the string.
const size_t vector_size = gift_bag.size();
for (unsigned int i = 0u; i < vector_size; ++i)
{
std::string& s(gift_bag[i]);
const size_t string_size = s.length();
for (unsigned int j = 0U; j < string_size; ++j)
{
Process_Character(s[j]);
}
}
There may be other methods, but you will need to consider that the strings may not be all the same length.

C++ Program to print the longest word of the string?

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
getline(cin , s) ; #input of string from user
int counter = 0;
int max_word = -1;
int len = s.length(); #length of string
string max = " ";
string counter_word = " ";
for (int i = 0; i < len; i++)
{
if(s[i] != ' ')
{
counter++;
}
if(s[i] == ' ' || i == len - 1)
{
if(counter > max_word)
{
max_word = counter;
//handling end of string.
if(i == len - 1)
max = s.substr(i + 1 - max_word, max_word); #sub string command that prints the longest word
else
max = s.substr(i - max_word, max_word);
}
counter = 0;
}
}
cout << max_word << " " << max << endl; #output
return 0;
}
The current output is '4 This' on entering the string "This is cool".
How do I get it to print '4 This; Cool' ?
On running it in Linux through the terminal, it gives me the error
" terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr Aborted (core dumped) "
If I have understood you correctly then you mean the following
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string s;
std::getline( std::cin, s );
std::string::size_type max_size;
std::string max_word;
std::string word;
std::istringstream is( s );
max_size = 0;
while ( is >> word )
{
if ( max_size < word.size() )
{
max_size = word.size();
max_word = word;
}
else if ( max_size == word.size() )
{
max_word += "; ";
max_word += word;
}
}
std::cout << max_size << ' ' << max_word << std::endl;
}
If to enter string
This is cool
then the output will be
4 This; cool
The basic idea here is to add each character to a temporary (initially empty) string until a space is encountered. At each instance of a space, the length of the temporary string is compared to the length of the "maxword" string, which is updated if it is found to be longer. The temporary string is emptied (reset to null using '\0') before proceeding to the next character in the input string.
#include <iostream>
#include <string>
using namespace std;
string LongestWord(string str) {
string tempstring;
string maxword;
int len = str.length();
for (int i = 0; i<=len; i++) {
if (tempstring.length()>maxword.length())
{
maxword=tempstring;
}
if (str[i]!=' ')
{
tempstring=tempstring+str[i];
}
else
{
tempstring='\0';
}
}
return maxword;
}
int main() {
cout << LongestWord(gets(stdin));
return 0;
}
#include <iostream>
using namespace std;
string longestWordInSentence(string str) {
// algorithm to count the number of words in the above string literal/ sentence
int words = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
words++;
}
}
// incrementing the words variable by one as the above algorithm does not take into account the last word, so we are incrementing
// it here manually just for the sake of cracking this problem
words += 1; // words = 5
// words would be the size of the array during initialization since this array appends only the words of the above string
// and not the spaces. So the size of the array would be equal to the number of words in the above sentence
string strWords[words];
// this algorithm appends individual words in the array strWords
short counter = 0;
for (short i = 0; i < str.length(); i++) {
strWords[counter] += str[i];
// incrementing the counter variable as the iterating variable i loops over a space character just so it does not count
// the space as well and appends it in the array
if (str[i] == ' ') {
counter++;
}
}
// algorithm to find the longest word in the strWords array
int sizeArray = sizeof(strWords) / sizeof(strWords[0]); // length of the strWords array
int longest = strWords[0].length(); // intializing a variable and setting it to the length of the first word in the strWords array
string longestWord = ""; // this will store the longest word in the above string
for (int i = 0; i < sizeArray; i++) { // looping over the strWords array
if (strWords[i].length() > longest) {
longest = strWords[i].length();
longestWord = strWords[i]; // updating the value of the longestWord variable with every loop iteration if the length of the proceeding word is greater than the length of the preceeding word
}
}
return longestWord; // return the longest word
}
int main() {
string x = "I love solving algorithms";
cout << longestWordInSentence(x);
return 0;
}
I have explained every line of the code in great detail. Please refer to the comments in front of every line of code. Here is a generalized approach:
Count the number of words in the given sentence
Initialize a string array and set the size of the array equal to the number of words in the sentence
Append the words of the given sentence to the array
Loop through the array and apply the algorithm of finding the longest word in the string. It is similar to finding the longest integer in an array of integers.
Return the longest word.
My original solution contained a bug: If you were to input 2 words of length n and 1 word of length n + k, then it would output those three words.
You should make a separate if condition to check whether the word length is the same as before, if yes, then you can append "; " and the other word.
This is what I would do:
Change if(counter > max_word) to if(counter >= max_word) so words of the same length are also taken into account.
Make the max string by default (so "" instead of " "). (See next point)
Add an if condition in the if(counter >= max_word)second if condition to see if the max string is not empty, and if it's not empty append "; "
Changing max = to max += so that it appends the words (in the second condition)
Wouldn't it be easier for you to split the whole line into a vector of string ?
Then you could ask the length of each element of the string and then print them. Because right now you still have all the words in a single string making each individual word hard to analyse.
It would also be hard, as you requested, to print all the words with the same length if you use a single string.
EDIT :
Start by looping through your whole input
Keep the greater length of word between the current one and the previously saved
Make a substring for each word and push_back it into a vector
Print the length of the bigger word
Loop through the vector and print each word of that size.
Look the following website for all references about vectors. dont forget to #include
www.cplusplus.com/reference/vector/vector/
#include <iostream>
#include <vector>
#include <string>
void LongestWord(std::string &str){
std::string workingWord = "";
std::string maxWord = "";
for (int i = 0; i < str.size(); i++){
if(str[i] != ' ')
workingWord += str[i];
else
workingWord = "";
if (workingWord.size() > maxWord.size())
maxWord = workingWord;
}
std::cout << maxWord;
}
int main(){
std::string str;
std::cout << "Enter a string:";
getline(std::cin, str);
LongestWord(str);
std::cout << std::endl;
return 0;
}
Source: http://www.cplusplus.com/forum/beginner/31169/
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,a;
char ch;
int len,mlen=0;
getline(cin,s);
char* token=strtok(&s[0]," ");
string r;
while(token!=NULL)
{
r=token;
len=r.size();
if(mlen<len)
{
mlen=len;
a=token;
}
token = strtok(NULL, " ");
}
cout<<a;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
string str;
getline(cin,str);
cin.ignore();
int len =str.length();`
int current_len=0,max_len=0;
int initial=0,start=0;
int i=0;
while(1)
{
if(i==len+2)
{break;}
if(str[i]==' '|| i==len+1)
{
if(current_len>max_len)
{
initial=start;
max_len=current_len;
}
current_len=0;
start=i+1;
}
else
{
current_len++;
}
i++;
}
for (int i = 0; i < max_len; i++)
{
cout<<str[i+initial];
}
cout<<endl<<max_len<<endl;
return 0 ;
}

All permutations of length k from n characters with repetition in CPP

I would like to know if there is already an implementation in CPP to find all permutations of n characters of length k(1,2,3,4 etc) with repetitions. I hope there is but i could not find.
For example if string= (A,B,C,D) and i want find all permutations of string with repetitions of length k =2.
The output will be something like :
AA
AB
AC
AD
.
.
.
DD
total permutations of 16.
Simple recursive solution which will work for you for sure.
Let me first re-write your specification: Print all permutations with repetition of characters
Given a string of length n, print all permutation of the given string.
Repetition of characters is allowed
For a given string of size n, there will be n^k possible strings of length "length". The idea is to start from an empty output string (we call it prefix in following code). One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for "length" equals to "length"-1.
#include <string>
#include <iostream>
void print_str(const char*,std::string,const int, const int);
int main()
{
int lenght = 2;
char str[] = {'A', 'B', 'C', 'D'};
int n = sizeof str;
print_str(str, "", n, lenght); //Note: this function works on all cases and not just the case above
return 0;
}
// The main recursive method to print all possible strings of length "length"
void print_str(const char str[],std::string prefix,const int n, const int lenght)
{
if (lenght == 1)
{
for (int j = 0; j < n; j++)
std::cout << prefix + str[j] << std::endl;
}//Base case: lenght = 1, print the string "lenght" times + the remaining letter
else
{
// One by one add all characters from "str" and recursively call for "lenght" equals to "lenght"-1
for (int i = 0; i < n; i++)
// Next character of input added
print_str(str, prefix + str[i], n, lenght - 1);
// "lenght" is decreased, because we have added a new character
}
}
Here is the execution of the code above:
References:
http://www.geeksforgeeks.org/print-all-permutations-with-repetition-of-characters/
http://www.geeksforgeeks.org/print-all-combinations-of-given-length/
Update: this update is writen answring the following spec.
I need one more help!! as i am new to CPP programming. Suppose if
length = 3 how can i make it to get all permutations starting from
length = 1 to length = 3 together in an array. Means to get all the
permutations of length =1, length =2 and length = 3 together stored in
an array
#include <string>
#include <iostream>
#include <vector>
void print_str(const char*,std::string,const int, const int);
std::vector<std::string> permutations ; // the vector permutations which will hold all the permutations,
//if you want you can use it for later use or you can use the array below which is nothing than a copy of this vector.
int NumberOfPermutations = 0; // this variable holds the number of permutations
int main()
{
int lenght = 3;
char str[] = {'A', 'B', 'C', 'D'};
int n = sizeof str;
//here we loop through all the possible lenghts 1, 2 and 3
for (int k = 1; k <= lenght; k++)
{
print_str(str, "", n, k); //Note: this function works on all cases and not just the case above
}
std::string* permut_array = new std::string[NumberOfPermutations]; // the array that we will use to store the permutations in
std::copy(permutations.begin(), permutations.end(), permut_array); // here we copy the vector into the array
//if you want you can use your array to print the permutation as folow
for (int k = 0; k < NumberOfPermutations; k++)
{
std::cout << permut_array[k] << std::endl;
}
return 0;
}
// The main recursive method to print all possible strings of length "length"
void print_str(const char str[],std::string prefix,const int n, const int lenght)
{
if (lenght == 1)
{
for (int j = 0; j < n; j++)
{
// i commented this ligne so that if you want to use your array to print your permutations you will not get a screnn with permutations printed 2 times
//std::cout << prefix + str[j] << std::endl;
permutations.push_back(prefix + str[j]); // the vector that we will use to store the permutations in
}
}//Base case: lenght = 1, print the string "lenght" times + the remaining letter
else
{
// One by one add all characters from "str" and recursively call for "lenght" equals to "lenght"-1
for (int i = 0; i < n; i++)
// Next character of input added
print_str(str, prefix + str[i], n, lenght - 1);
// "lenght" is decreased, because we have added a new character
}
NumberOfPermutations = permutations.size();
}
you can use std::next_permutation() as πάντα ῥεῖ said, but since you want to define the length and the char with repetitions, you can do something easy to realize it, as:
std::string s = "aabbccdd";
std::set<std::string> string_set;
std::sort(s.begin(), s.end());
do {
string_set.insert(s.substr(0, 2));
} while(std::next_permutation(s.begin(), s.end()));
for(auto i = string_set.begin(); i != string_set.end(); ++i)
std::cout << *i << std::endl;
This just isn't a permutation, which probably explains why you can't find an answer.
What you are actually asking is how to print the numbers 0..k-1 in base n, using digits A,B,C,D. I'll rewrite your example with familiar digits 0,1,2,3 :
00
01
02
03
10
11
12
13
..
33
There's no standard C++ method for this, but now that you know what it's called there's plenty of code on the web. Or just write it yourself. Hint: the last digit of i has value i % n.
This solution works out for all standard container and also static arrays. I think this can be used also for classes and structures
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <list>
#include <iterator>
template<typename InputIt, typename T>
bool nextPermutationWithRepetition(InputIt begin, InputIt end, T from_value, T to_value) {
auto it = std::find_if_not(std::make_reverse_iterator(end),
std::make_reverse_iterator(begin),
[&to_value](auto current) { return to_value == current; });
if (it == std::make_reverse_iterator(begin))
return false;
auto bound_element_iterator = std::prev(it.base());
(*bound_element_iterator)++;
std::fill(std::next(bound_element_iterator), end, from_value);
return true;
}
int main() {
std::list<int> vec(3, 0);
do {
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
} while (nextPermutationWithRepetition(vec.begin(), vec.end(), 0, 2));
return 0;
}