-2

I have written the program to sum if at least one character is common in the vector of string in c++, for that I have used set_intersection function.I am getting segmentation fault donot know why.

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int matching_characters(string s1, string s2);

int main()
{
    string s;
    vector<string> ss;
    int n,sum=0,avg=0;
    cout<<"enter no in group"<<endl;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin >> s;
        ss.push_back(s);

    }
   // cout<<ss[1];

 // cout<<ts[1];
 for(int i=1;i<=n;i++)
 {

    for(int j=1;j<=n;j++)
    {
     if(i==j)
     continue;
    int t=matching_characters(ss[i], ss[j]);
    cout<<t;
    if(t!=0)
     sum=sum+1; 
    }
 }

    cout<<"'s='"<<sum<<endl;
    //avg=sum/n;
    //cout<<avg;
     return 0;
}

int matching_characters(string s1, string s2) {
  sort(s1.begin(), s1.end());
  sort(s2.begin(), s2.end());
  string intersection;
  set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
                        back_inserter(intersection));
  return intersection.size();
}

enter image description here

001
  • 13,291
  • 5
  • 35
  • 66
  • Please post your code as text in your question. – NathanOliver Sep 17 '18 at 13:40
  • 4
    `for(int i=1;i<=n;i++)` Indexes start at `0`. Try `for(int i = 0; i < n; i++)` – 001 Sep 17 '18 at 13:44
  • 2
    When using `vector` you can use [`at`](https://en.cppreference.com/w/cpp/container/vector/at) instead of `[]`. This will throw an exception for a bad index. – 001 Sep 17 '18 at 13:51

1 Answers1

1

I think that

for(int i=1;i<=n;i++)
{
    for(int j=1;j<=n;j++)
    {
        if(i==j)
            continue;

would be better written as

for(int i=0;i<n;i++)
{
    for(int j=i+1;j<n;j++)
    {

Bearing in mind that an array of n objects has valid indices [0]...[n-1], we start from 0 in the first loop, and we stop iterating before we get to the invalid index n. For efficiency, we start the second loop at a point that skips more than half of the comparisons. (There's no point comparing A with A, and after comparing A with B there's no point comparing B with A.)

Tim Randall
  • 4,040
  • 1
  • 17
  • 39