-2

I am trying to remove duplicates from a string. The code goes like:

#include<iostream>
#include<stdio.h>
#include<string.h>

void removeDup(std::string s, std::string &ex)
{
    int hash[256] = {0};
    int k = 0;
    for (int i = 0; i < s.size(); ++i)
    {
        if (hash[s[i]] == 0)
        {
            ex[k++] = s[i];
            //std::cout<<ex[k-1];
        }
        hash[s[i]] = 1;
    }
}

int main()
{
    std::string s;
    std::getline(std::cin, s);
    std::string ss;

    removeDup(s, ss);
    std::cout<<ss<<std::endl;
    return 0;
}

Now in main function I have printed the value of ss (which is passed as reference in removeDup function) but it prints nothing. Why is it so? Doesn't the value of string elements gets updated in called function?

Also, when I pass the string by address then I just get the first value printed.

eg :

void removeDup(std::string s, std::string *ex)
{
    // same as above body function body
}

int main()
{
......
    removeDup(s, &ss);
    std::cout<<ss<<std::endl;
    return 0;
}

In the output I just get the first letter of whatever is there in s. I can't understand. I am not much familiar with strings in programming languages. Kindly help.

haunted
  • 27
  • 5
  • 1
    Undefined behavior, that's all. You might want to check your character accesses. – Rakete1111 Sep 03 '17 at 19:17
  • You are trying to assign characters while `ex` is empty at `ex[k++] = s[i];`. You should push characters into it instead. – user7860670 Sep 03 '17 at 19:21
  • @Rakete1111 didn't get you. I read something [here](https://stackoverflow.com/questions/10789740/passing-stdstring-by-value-or-reference) and then thought of doing this. – haunted Sep 03 '17 at 19:21
  • The first iteration of the `for` loop performs an assignment `ex[0] = s[0]`. Have you tried to see what such assignment does to an empty `string` variable? – CiaPan Sep 03 '17 at 19:22
  • Use `+=` to add the output string and get rid of `k` completely. https://ideone.com/XB993L Don't include C headers you don't need, but do include the proper C++ headers. – Retired Ninja Sep 03 '17 at 19:43

1 Answers1

2

This comes down to the fact that std::string::operator[](size_t index) expects passed index to be lower that string's size().

That means you need to either initialize ss with constructor (variant 2) that will fill it with input's size() worth of ' ''s or, better, use push_back() (ideally in conjunction with reserve() as a way to append elements to the output string.

orhtej2
  • 2,133
  • 3
  • 16
  • 26