Larrimus
Larrimus

Reputation: 211

Assertion Failure when trying to Swap two Elements in a Vector

I have this code:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <stdint.h>

std::vector<std::string> readIn(const std::string& fileName)
{
    std::vector<std::string> strVec;
    std::ifstream file(fileName);
    std::string line;
    while (!file.eof())
    {
        file >> line;
        strVec.push_back(line);
    }
    file.close();
    return strVec;
}
void sortVector(std::vector<std::string>& strVec)
{
    size_t size = strVec.size();
    for (size_t j = 4; j >= 0; j--)
    {
        for (size_t i = 0; i < size; i++)
        {
            for (size_t k = i; strVec[k][j] > strVec[k + 1][j]; k++)
                strVec[k].swap(strVec[k+1]); //CRASHES HERE
        }
    }
}
int main()
{
    std::string fileName = "input.txt";
    std::vector<std::string> strVec = readIn(fileName);
    size_t size = strVec.size();
    std::cout << "Words in file:" << std::endl
        << "before sorting:";
    for (size_t i = 0; i < size; i++)
        std::cout << strVec[i] << " ";
    sortVector(strVec);
    std::cout << std::endl << std::endl << "after sorting:" << std::endl;
    for (size_t i = 0; i < size; i++)
        std::cout << strVec[i] << std::endl;
    return 0;
}

The problem I'm having with this is sorting the strings my vector. More specifically, the program isn't fond of strVec[k].swap(strVec[k+1]); in my sortVector() function. The debugger also says that my vector is being filled correctly:
enter image description here
So readIn() doesn't appear to be the problem (as the program breaks while in sortVector()), but I posted it anyways.

Perhaps I shouldn't be giving up so quickly, but I've Googled this and read everything I can about vectors (and strings in vectors), and I'm still stumped. Any feedback you guys can give would be greatly appreciated.

Edit: Here's the contents of my input.txt file:

This is a test input file for CS250's CS161 programming pre-requisite assignment

This file contains a number of words and lines, but nothing terribly important.

Upvotes: 1

Views: 60

Answers (1)

R Sahu
R Sahu

Reputation: 206577

One problem I see is that you don't have any checks to make sure that you don't access the vector out of bounds.

Change

for (size_t k = i; strVec[k][j] > strVec[k + 1][j]; k++)
    strVec[k].swap(strVec[k+1]);

to

for (size_t k = i; k < size-1 && strVec[k][j] > strVec[k + 1][j]; k++)
    strVec[k].swap(strVec[k+1]);

Since you are accessing strVec[k+1], k must be less than size-1.

That will lead to problems if size is 0. You can get around that problem by using int for size and k instead of size_t.

Upvotes: 2

Related Questions