I'm working on code for a container that stores strings and sorts them in alphabetical order (thought that it'd be a fun idea). I've been attempting to put a "[]" operator and assign it to the private member words so I can access any data or strings inside of said member. However, I've been struggling with this continuous error that I'm having trouble fixing. It says:
No operator "[]" matches these operands. Operand types are std::shared_ptr<std::vector<std::string, std::allocator<std::string>>>[size_t]
Here's some of the code regarding the error (Error is present at class.cpp):
class.h
#pragma once
#include <memory>
#include <vector>
#include <string>
#include <iostream>
class sort
{
public:
//...
sort(int i): words(std::make_shared<std::vector<std::string>>(i)) { }
std::shared_ptr<std::vector<std::string>> & operator [](size_t st);
//...
private:
std::shared_ptr<std::vector<std::string>> words;
std::string alpha = "abcdefghijklmnopqrstuvwxyz";
};
class.cpp
#include "sort.h"
#include <memory>
#include <vector>
#include <iostream>
//...
std::shared_ptr<std::vector<std::string>> & sort::operator[](size_t st)
{
return words[st]; //Error is defined at the brackets
}
//...
Another thing to note is that if I remove the brackets with st
, the error is gone (Obviously not what I'm trying to achieve). Any help or a fix to this code would be greatly appreciated.
Your words
member is not an array or container. It is a std::shared_ptr
, which does not have an operator[]
defined prior to C++17 (and even then, your code would still be using it wrong). That is why your operator[]
fails to compile.
You have a std::shared_ptr
pointing to a std::vector<std::string>
object stored somewhere else in memory 1. If you want your operator[]
to access the std::string
values in that std::vector
, you need to deference the pointer first in order to access the std::vector
, and then you can call its operator[]
. You need to fix the return value of your operator[]
to be a single std::string
, not a std::shared_ptr
.
1: why are you using a pointer at all? Why not declare words
to be an actual std::vector
object directly in your class? std::vector<std::string> words;
Try this instead:
class.h
#pragma once
#include <memory>
#include <vector>
#include <string>
#include <iostream>
class sort
{
public:
//...
std::string& operator [](size_t st);
//...
private:
std::shared_ptr<std::vector<std::string>> words;
std::string alpha = "abcdefghijklmnopqrstuvwxyz";
};
class.cpp
#include "sort.h"
#include <memory>
#include <vector>
#include <iostream>
//...
std::string& sort::operator[](size_t st)
{
return (*words)[st];
}
//...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments