C++: Array and String

什么是array

Arrays in C/C++ - GeeksforGeeksA Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.https://www.geeksforgeeks.org/arrays-in-c-cpp/?ref=leftbar-rightbar

An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.  They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as the structures, pointers etc.

Why do we need arrays? 

We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.

What is Array Decay in C++? How can it be prevented?

What is Array Decay in C++? How can it be prevented? - GeeksforGeeksA Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.https://www.geeksforgeeks.org/what-is-array-decay-in-c-how-can-it-be-prevented/What is Array Decay? 
The loss of type and dimensions of an array is known as decay of an array.This generally occurs when we pass the array into function by value or pointer. What it does is, it sends first address to the array which is a pointer, hence the size of array is not the original one, but the one occupied by the pointer in the memory.

How to prevent Array Decay? 
A typical solution to handle decay is to pass size of array also as a parameter and not use sizeof on array parameters.  (常见写法)
Another way to prevent array decay is to send the array into functions by reference. This prevents conversion of array into a pointer, hence prevents the decay.

// C++ code to demonstrate prevention of
// decay of array
#include<iostream>
using namespace std;

// A function that prevents Array decay (这种写法之前没见过)
// by passing array by reference
void fun(int (&p)[7])

{
    // Printing size of array
    cout << "Modified size of array by "
            "passing by reference: ";
    cout << sizeof(p) << endl;
}

int main()
{
    int a[7] = {1, 2, 3, 4, 5, 6, 7,};

    // Printing original size of array
    cout << "Actual size of array is: ";
    cout << sizeof(a) <<endl;

    // Calling function by reference
    fun(a);

    return 0;
}

std::string class in C++

C++ has in its definition a way to represent sequence of characters as an object of class. This class is called std:: string. String class stores the characters as a sequence of bytes with a functionality of allowing access to single byte character

std:: string vs Character Array

  • A character array is simply an array of characters can terminated by a null character. A string is a class which defines objects that be represented as stream of characters.
  • Size of the character array has to allocated statically, more memory cannot be allocated at run time if required. Unused allocated memory is wasted in case of character array. In case of strings, memory is allocated dynamically. More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted.\

  • There is a threat of array decay in case of character array. As strings are represented as objects, no array decay occurs.

  • Implementation of character array is faster than std:: string. Strings are slower when compared to implementation than character array.

  • Character array do not offer much inbuilt functions to manipulate strings. String class defines a number of functionalities which allow manifold operations on strings.

Operations on strings

Input Functions
1. getline() :- This function is used to store a stream of characters as entered by the user in the object memory.
2. push_back() :- This function is used to input a character at the end of the string.
3. pop_back() :- Introduced from C++11(for strings), this function is used to delete the last character from the string.

Capacity Functions
4. capacity() :- This function returns the capacity allocated to the string, which can be equal to or more than the size of the string. Additional space is allocated so that when the new characters are added to the string, the operations can be done efficiently.
5. resize() :- This function changes the size of string, the size can be increased or decreased.
6.length():-This function finds the length of the string
7.shrink_to_fit() :- This function decreases the capacity of the string and makes it equal to the minimum capacity of the string. This operation is useful to save additional memory if we are sure that no further addition of characters have to be made.

Iterator Functions
8. begin() :- This function returns an iterator to beginning of the string.
9. end() :- This function returns an iterator to end of the string.
10. rbegin() :- This function returns a reverse iterator pointing at the end of string.
11. rend() :- This function returns a reverse iterator pointing at beginning of string.

Manipulating Functions
12. copy(“char array”, len, pos) :- This function copies the substring in target character array mentioned in its arguments. It takes 3 arguments, target char array, length to be copied and starting position in string to start copying.
13. swap() :- This function swaps one string with other.

string c_str() vs. data()

The documentation is correct. Use c_str() if you want a null terminated string.

If the implementers happend to implement data() in terms of c_str() you don't have to worry, still use data() if you don't need the string to be null terminated, in some implementation it may turn out to perform better than c_str().

strings don't necessarily have to be composed of character data, they could be composed with elements of any type. In those cases data() is more meaningful. c_str() in my opinion is only really useful when the elements of your string are character based. (如果string是非char, 调用c_str()返回的也不是char字符,只是char stream 而已)

Extra: In C++11 onwards, both functions are required to be the same. i.e. data is now required to be null-terminated. According to cppreference: "The returned array is null-terminated, that is, data() and c_str() perform the same function."

Raw string literal in C++

In C++, to escape characters like “\n” we use an extra “\”. From C++ 11, we can use raw strings in which escape characters (like \n \t or \” ) are not processed(所见即所得). The syntax of raw string is that the literal starts with R”( and ends in )”.

Let’s see an example to see raw string literal in C++:

// C++ program to demonstrate working of raw string.
#include <iostream>
using namespace std;

int main()
{
    // A Normal string
    string string1 = "Geeks.\nFor.\nGeeks.\n" ;

    // A Raw string
    string string2 = R"(Geeks.\nFor.\nGeeks.\n)";

    cout << string1 << endl;

    cout << string2 << endl;
    
    return 0;
}

Output:

Geeks.
For.
Geeks.

Geeks.\nFor.\nGeeks.\n
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值