修改向量的元素(按值,通过引用)函数C ++ [英] Modify elements of vector (by value, by reference) Function C++

查看:185
本文介绍了修改向量的元素(按值,通过引用)函数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我必须修改一个向量的值。
是C ++中返回vector的好习惯吗?

函数1:



 矢量<串GT; RemoveSpecialCharacters(vector< string> words)
{
for(vector< string> :: iterator it = words.begin(); it!= words.end();)
{
if(CheckLength(* it)== false)
{
it = words.erase(it);
}
else {
++ it;
}
} //结束为

返回单词;



功能2:



  void RemoveSpecialCharacters(vector< string>& words)
{
for(vector< string> :: iterator it = words .begin(); it!= words.end();)
{
if(CheckLength(* it)== false)
{
it = words.erase它);
}
else {
++ it;
}
} //结束为
}


解决




  • 函数1:作为 remove_copy 。它不会修改现有的容器;它会复制并修改它。

  • 它会修改现有的容器。

I have a function where I have to modifiy the values of a vector. is it a good practice in C++ to return the vector?

Function 1:

vector<string> RemoveSpecialCharacters(vector<string> words)
{
    for (vector<string>::iterator it=words.begin(); it!=words.end(); )
    {
        if(CheckLength(*it) == false)
        {
            it = words.erase(it);
        }
        else{
            ++it;
        }
    }//end for

    return words;
}

Function 2:

void RemoveSpecialCharacters(vector<string> & words)
{
    for (vector<string>::iterator it=words.begin(); it!=words.end(); )
    {
        if(CheckLength(*it) == false)
        {
            it = words.erase(it);
        }
        else{
            ++it;
        }
    }//end for
}

解决方案

Your two functions serve for two different purposes.

  • Function 1: works as remove_copy. It will not modify the existing container; it makes a copy and modifies that instead.

  • Function 2: works as remove. It will modify the existing container.

这篇关于修改向量的元素(按值,通过引用)函数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆