I am trying to complete an assignment for beginner comp sci. We are just learning about space allocation and using headers, as well as dynamic memory allocation. One of the requirements is that we have to use unnamed namespace in a header for our const variable and the function declaration. I receive a compiling error on line 28 about "undefined reference to anonymous namespace" I am unsure how to fix this or what syntax or typo is causing it. We are just learning about this so don't judge too harshly haha.
mylibrary.hpp
#include <iostream>
#include <memory>
#ifndef MYLIBRARY_HPP
#define MYLIBRARY_HPP
namespace
{
int counter = 0;
const int SIZE = 10;
std::unique_ptr<char[]> deleteRepeats(char arr[]);
}
#endif // MYLIBRARY_HPP
main.cpp
using std::cin;
using std::cout; //using declarations to avoid namespace std
using std::endl;
int main()
{
char originalArray[SIZE]; //declaration of array that will be used in the program and all its values
originalArray [0] = 'a';
originalArray [1] = 'b';
originalArray [2] = 'b';
originalArray [3] = 'c';
originalArray [4] = 'a';
originalArray [5] = 'c';
originalArray [6] = 'a';
originalArray [7] = 'c';
originalArray [8] = 'b';
originalArray [9] = 'c';
std::unique_ptr<char[]> noRepeats = deleteRepeats(originalArray); //function call
cout << "the amount of repeats is... " << SIZE-counter << endl; //prints out the number of repeats
for(int i =0; i<counter; i++) //displays new array
{
cout << noRepeats[i] << endl;
}
return 0;
}
function.cpp
#include <iostream>
#include <memory>
//my function definitions
namespace
{
//Precondition: an array of defined size contains only valid characters
//Postconition: a new array is generated with only unique values
std::unique_ptr<char[]> deleteRepeats(char arr[]) //goes through the array and checks if it has repeats
{
for(int i=0; i<SIZE/2; i++)
{
if(arr[i] = arr[SIZE -1-i]) //marks any repeats
{
arr[i] = '-';
arr[SIZE-1-i] = '-';
}
}
for(int i =0; i<SIZE; i++) //counts new array
{
if(arr[i] != '-')
{
counter++;
}
}
std::unique_ptr<char[]> newArray(new char[counter]); //declares a new array using a pointer
int location = 0;
for(int i = 0; i<SIZE; i++)
{
if(arr[i] != '-')
{
newArray[location++] = arr[i];
}
}
return newArray;
}
}
//Postconition: a new array is generated with only unique values-- There are far more easier ways to do this than your attempt.std::sortand thenstd::unique, or simply store everything into astd::set, and create a new array from thestd::setcontents.